Powershell error handling

Welcome Forums General PowerShell Q&A Powershell error handling

This topic contains 2 replies, has 3 voices, and was last updated by

2 months, 1 week ago.

  • Author
  • #151833

    Topics: 1
    Replies: 0
    Points: 19
    Rank: Member

    Hi, I have the following powershell script and i am trying to catch the error using "ErrorActionPreference='silentlycontinue" followed by try, catch block but cant execute the script. Where can i implement the erroraction command and use try, catch block. Thank you.


    $computers = dsquery computer ou=WorkSpaces,dc=xyz,dc=com -o rdn | % {$_ -replace '"', ""}

    Foreach ($Machine in $computers) {

    $Session = New-PSSession -Computername $Machine

    $DExists =Invoke-Command -session $session {test-path "C:\Program Files .................."}

    If ($DExists) {

      Copy-Item -Path \ -Destination '

      write-host "copy completed $machine"

    } else {

      write-host "directory not found $machine"


    Remove-PSSession -Session $session


  • #151851

    Topics: 8
    Replies: 891
    Points: 2,749
    Helping Hand
    Rank: Community Hero

    Please update your post by formatting the code(use gist.github.com to post the code). Error can happen in multiple areas in the above snippet, Error handling is depended on where you want to handle it.

    You can have the whole code snippet in a try catch block. But you have to use -ErrorAction Stop, if you use silentlycontinue, the execution gets continued with out jumping to catch block.

  • #151920

    Topics: 2
    Replies: 442
    Points: 924
    Helping Hand
    Rank: Major Contributor

    Setting the $ErrorActionPreference to SilentlyContinue will actively prevent most errors from triggering the try/catch block.

    If you want to trigger the try/catch block, you need to set it to Stop.

You must be logged in to reply to this topic.