Reputation: 2965
I'm having trouble getting Test-Path to work from the pipeline. For some reason the command always evaluates to false and executes the commands contained in the IF statement.
The code looks like this:
$BACKUPFOLDER = "F:\TEST\Old\"
Get-ChildItem "$SrcFolder\*.pgp" | Where-Object {!$_.PsIsContainer} | ForEach-Object {
Add-Content -Path $LOGFILE -Value "`r`n - Decrypting file $_ -"
Decrypt-Files $_ "$SrcFolder$($_.BaseName)" $Credential $DecryptionLogFile
if (!(Test-Path "$BackupFolder$($_.BaseName)")) {
Add-Content -Path $LOGFILE -Value "`n`rMoving $_ to $BackupFolder"
Move-Item $_ $BackupFolder
}
else {
Add-Content -Path $LOGFILE -Value "`n`rCould not move $_ to $BackupFolder. Destination file already exists."
}
The error I get is with the Move-Item command:
Move-Item : Cannot create a file when that file already exists.
At F:\Scripting\1-Dev\Modules\Include.ps1:505 char:26
+ Move-Item <<<< $_ $BackupFolder
+ CategoryInfo : WriteError: (F:\TEST...201301.xlsx.pgp:FileInfo) [Move-Item], IOException
+ FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand
I'm confused because the file already exists in the backup folder, yet for some reason the script still goes through the IF statement and executes the move-item command. Is my syntax bad for Test-Path?
The file I'm decrypting will be named something like VPAS-201301.xlsx.pgp and the file I'm extracting will be VPAS-201301.xlsx.
Upvotes: 0
Views: 332
Reputation: 8650
You are testing $_.BaseName
(that is: name of the file without extension). Use $_.Name
and you should get expected results.
Upvotes: 1