Chris
Chris

Reputation: 88

Powershell: cannot hide 'Access is denied' error on 'Remove-Item'

I would like to keep a Remove-Item instruction quiet, exception or not. I'm running below command in a script to delete a certificate:

Remove-Item $store\$thumbprint

If I run the script as local Admin, fine... it keeps quiet and the file is deleted. If however I run it as unpriviledged user, I get an 'Access in denied' error as expected, but I would like to keep this quiet in any case.

I've tried the following:

$output = (Remove-Item $store\$thumbprint)
# or...
try{Remove-Item $store\$thumbprint} catch{}
# or...
Remove-Item $store\$thumbprint -ErrorAction SilentlyContinue

But I always get the error/exception displayed on the console.

Upvotes: 0

Views: 3093

Answers (1)

JosefZ
JosefZ

Reputation: 30113

By default, a non-terminating error is generated by Remove-Item and it adds an error to the $Error variable without throwing an exception. To see what Windows PowerShell will do when a non-terminating error arises, look at the value of the $ErrorActionPreference variable (its default value is Continue).

The Access to the path '…' is denied is an example of such a non-terminating error so you can use ErrorAction parameter which overrides the value of the $ErrorActionPreference variable for the current command:

Remove-Item $store\$thumbprint -ErrorAction SilentlyContinue

On the other side, $ErrorActionPreference and the ErrorAction parameter don't affect how PowerShell responds to terminating errors that stop cmdlet processing. So if we are not sure whether an error is terminating or not then it's safe to handle any error the Try-Catch-Finally blocks using -ErrorAction Stop as follows:

try {
    Remove-Item $store\$thumbprint -ErrorAction Stop
} catch {
    ### A Catch block can include commands for tracking the error
    ###         or for recovering the expected flow of the script
}

Upvotes: 1

Related Questions