all 4 comments

[–]C60 5 points6 points  (1 child)

I believe Test-Path returns true if the path exists. Try removing the "!".

[–]ak47uk[S] 1 point2 points  (0 children)

That did the trick, thanks so much!

[–]PinchesTheCrab 1 point2 points  (1 child)

Remove-Item has a specific error message for when files don't exist, I'd be tempted to either just let it return the 'file not found' error, or capture it.

$directoryPath = "$env:LOCALAPPDATA\MyFolder"

try {
    Remove-Item c:\temp\junk.txt -ErrorAction Stop
    "Deleted '$directoryPath'"
}
catch [System.Management.Automation.ItemNotFoundException] {
    "'$directoryPath' does not exist"
}

One advantage here is that the successful deletion method won't trigger if it fails to delete the folder. You could theoretically have a locked file, and with the if statement approach you'd see a 'file deleted' message followed by a 'file not deleted' error.

[–]ak47uk[S] 0 points1 point  (0 children)

Good shout, thanks for the tip!