PowerShell Try/Catch not working

powershell

I have a script that I am writing to replace our company's wallpaper. The script runs fine as an admin, but I want to catch it if it doesn't. Here's a snip of the code (Write-Log is a function that writes to a custom log file in our Logs folder)

try{
    Write-Log "Attempting to copy new wallpaper"
    Copy-Item $PSScriptRoot\img0.jpg C:\windows\WEB\wallpaper\Windows\img0.jpg | Out-Null
    Copy-Item $PSScriptRoot\4k\*.* C:\Windows\Web\4K\Wallpaper\Windows | Out-Null
    Write-Log "Task completed."
}catch{
    write-Log("Error occured:"+$Error[0].Exception.Message )
}

It throws the following error for all the files when run as a non-admin without rights to the fodler.

Copy-Item : Access to the path 'C:\windows\WEB\wallpaper\Windows\img0.jpg' is denied.

Shouldn't the Catch part catch that the copy-item doesn't have permissions?

Best Answer

Try blocks catch only terminating errors, and failure to copy a file is not one. You can force the Copy-Item to terminate on failure by adding

$ErrorActionPreference = "Stop"

to the beginning of your script. This way, any error will count as a terminating error, so control will jump to the catch block.