Powershell error handling

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.

<p class=“p1”>$computers = dsquery computer ou=WorkSpaces,dc=xyz,dc=com -o rdn | % {$_ -replace ‘"’, “”}</p>
<p class=“p3”>Foreach ($Machine in $computers) {</p>
<p class=“p3”>$Session = New-PSSession -Computername $Machine</p>
<p class=“p4”>$DExists =Invoke-Command -session $session {test-path “C:\Program Files …”}</p>
<p class=“p3”>If ($DExists) {</p>
<p class=“p4”> Copy-Item -Path </span> -Destination '</p>
<p class=“p4”> write-host “copy completed $machine”</p>
<p class=“p5”>} else {</p>
<p class=“p4”> write-host “directory not found $machine”</p>
<p class=“p5”>}</p>
<p class=“p6”>Remove-PSSession -Session $session</p>
<p class=“p7”>}</p>

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.

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.