0

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?

1
  • Try to divide your script into two try-catch blocks
    – Maxiko
    Commented Mar 10, 2020 at 12:44

3 Answers 3

3

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.

1
  • Could MSFT have made PowerShell any more complicated and unintuitive? No, they couldn't have.
    – RonJohn
    Commented May 26, 2023 at 20:40
1

You can set a common parameter ErrorAction value to Stop to catch non-terminating errors on catch block. Or you can set the value of preference variable as shown in the other answer. Like:

Cmdlet -Parameters Value -ErrorAction Stop 

0

FYI, I had a statement which even though it had the -ErrorAction Stop at the end, would not stop and just continued running.

I added $ErrorActionPreference = "Stop" to the code and it worked the way I intended then I removed it and it still worked as intended!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .