Callum Stones
Callum Stones

Reputation: 35

Try Catch Query Powershell

Can anyone advise why when I run this script I still get a generic error generated by powershell? It is nested in an IF statement originally.

try {

Remove-Item -Path "C:\Users$env:USERNAME\AppData\Local\Microsoft\Outlook" -Force -Recurse | Out-Null

} catch { "Appdata Cache does not exist!"

}

Upvotes: 1

Views: 33

Answers (1)

Fitzgery
Fitzgery

Reputation: 718

catch only works on terminating errors. So you’ll have to change your try statement to. Also you’re missing a “\” in your path

Try{

    Remove-Item C:\Users\$env:USERNAME\AppData\Local\Microsoft\Outlook" -Force -Recurse -ErrorAction Stop

}Catch{

    “Appdata cache doesn’t exist”

}

Also Remove-Item doesn’t return an object so you don’t need to redirect it to null

Upvotes: 2

Related Questions