Powershell Foreach循环查找文件名,但返回它们不存在

时间:2016-05-31 17:05:24

标签: powershell gnupg

以下是我的代码的相关摘录:

$CurDir = Split-Path $Script:MyInvocation.MyCommand.Path
Get-ChildItem -Path $CurDir -Filter TestFile*.txt | foreach { 
    gpg --recipient "RecipName" --encrypt $_ }

但是,这是返回的内容:

gpg: can't open `TestFileForENcryption - Copy (2).txt': No such file or  direct
gpg: TestFileForENcryption - Copy (2).txt: encryption failed: No such file or
gpg: can't open `TestFileForENcryption - Copy (3).txt': No such file or direct
gpg: TestFileForENcryption - Copy (3).txt: encryption failed: No such file or
gpg: can't open `TestFileForENcryption - Copy.txt': No such file or directory
gpg: TestFileForENcryption - Copy.txt: encryption failed: No such file or dire
gpg: can't open `TestFileForENcryption.txt': No such file or directory
gpg: TestFileForENcryption.txt: encryption failed: No such file or directory

如果它能够找到这些文件中的每一个以在GCI期间获取名称,为什么在尝试对它们执行操作时它们不存在? 任何帮助赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

$CurDir = Split-Path $Script:MyInvocation.MyCommand.Path
Get-ChildItem -Path $CurDir -Filter TestFile*.txt | foreach { 
    gpg --recipient "RecipName" --encrypt $_.FullName }

我相信你的错误只是它有$_,它只提供文件的名称,而不是FQPN(完全限定的路径名​​)。

有关如何以不同方式使用Name / FullName的详细信息,请参阅here

答案 1 :(得分:1)

可能是因为这些文件不在gpg的工作目录中。尝试使用FullName属性告诉它文件的完整路径:

Get-ChildItem -Path $CurDir -Filter TestFile*.txt | foreach { 
    gpg --recipient "RecipName" --encrypt "$($_.FullName)" }