max
max

Reputation: 1

Powershell Foreach Loop finds file names, but returns that they don't exist

Here is the relevant excerpt of my code:

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

However, this is what is returned:

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

If it's able to locate each of these file's to get the names during GCI, why is it saying that they don't exist when trying to perform an action on them? Any help appreciated. Thanks!

Upvotes: 0

Views: 214

Answers (2)

zdan
zdan

Reputation: 29450

It's likely because those files aren't in the working directory of gpg. Try telling it the full path of the files by using the FullName property:

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

Upvotes: 1

gravity
gravity

Reputation: 2066

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

I believe your error was simply it having $_, which only gives the name of the file, as opposed to the FQPN (fully qualified path name).

See here for details as to how Name/FullName are utilized differently.

Upvotes: 1

Related Questions