Test-Path Gotchas

Welcome Forums General PowerShell Q&A Test-Path Gotchas

Viewing 5 reply threads
  • Author
    Posts
    • #217647
      Participant
      Topics: 1
      Replies: 1
      Points: -6
      Rank: Member

      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
      }

       

    • #217671
      Participant
      Topics: 4
      Replies: 2247
      Points: 5,484
      Helping Hand
      Rank: Community MVP

      I’d do it this way …. 😉

      $TestPath = "$env:SystemDrive:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\file.lnk"
      if (Test-Path -Path $TestPath){
          Remove-Item -Path $TestPath -Force -ErrorAction SilentlyContinue
      }
    • #217674
      Participant
      Topics: 3
      Replies: 340
      Points: 1,120
      Helping Hand
      Rank: Community Hero

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

    • #217677
      Participant
      Topics: 1
      Replies: 1
      Points: -6
      Rank: Member

      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.

    • #217716
      Participant
      Topics: 12
      Replies: 523
      Points: 1,214
      Helping Hand
      Rank: Community Hero

      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..

    • #218238
      Senior Moderator
      Topics: 8
      Replies: 1215
      Points: 4,335
      Helping Hand
      Rank: Community Hero

      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.

Viewing 5 reply threads
  • You must be logged in to reply to this topic.