Test-Path Gotchas

Hi all! Apologies ahead of time if this has been covered. Any help you can provide would be very much appreciated!

I’m running into a problem with the test-path cmdlet , which i’m certain is a result of my method. When I leverage test-path within a variable it keeps the result value of the time it was set. Even if the result is true, it will still return false and vice versa. What I’m trying to do is test for the existence of a value within an if-else statement.

if ($testpath -eq $true)
Remove-Item -Path “$env:SystemDrive:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\file.lnk” -Force -ErrorAction SilentlyContinue


I’d do it this way … :wink:

$TestPath = "$env:SystemDrive:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\file.lnk"
if (Test-Path -Path $TestPath){
    Remove-Item -Path $TestPath -Force -ErrorAction SilentlyContinue

I think a bit more context would be helpful. Can you show your variable and test-path code?

That did it for me Olaf, thank you! I see now I was going about it the opposite way.

Have a good and safe weekend during these quarantine times.

uhm, why test for the path?

Remove-Item -Path “$env:SystemDrive:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\file.lnk” -Force -ErrorAction SilentlyContinue

would just work as is. If the file exists it will delete it, if it does not it will not error out…

Setting -ErrorAction to silently continue depends on how you are depended on the cmdlet execution. Here if the script expects the path to be deleted to proceed with some other decision down in the script, then it won’t be a good option, otherwise its a possible solution.

Because there are many reasons why an error can occur.