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

问题描述:

这里是我的代码的相关摘录:PowerShell的Foreach循环查找的文件名,但返回它们不存在

$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期间找到这些文件中的每个文件以获取名称,为什么在尝试对它们执行操作时说它们不存在? 任何帮助表示赞赏。谢谢!

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

我相信你的错误只是有$_,只给出了文件的名称,而不是在FQPN(完全合格的路径名)吧。

有关详细信息,请参阅here以了解名称/全名的使用方式。

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

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

感谢您的答案!我的问题有两个:当手动测试这段代码时,我从错误的目录中解释了“没有这样的文件或目录”。 它没有从任务计划程序运行(我开始进行故障排除的时候),因为在导入gnupg中无人参与运行的某些内容时,必须在--import之前使用--home-directory命令。 – max