2

I have a simple script to delete a file, I know it could be more robust, but here it is

$LogFile = ".\deleteRegPol.log"

try
{
    Remove-Item "c:\test\new text document.txt" -force
    Add-Content $LogFile -Value "We ran the command"
}
catch [Exception]
{
    Add-Content $LogFile -Value $_
}
finally
{
}

When the file I am trying to delete doesn't exist, I get an error on the command line but in my log file, it says the command ran. This is telling me that an exception was not thrown resulting in the flow going to the catch block. Why not?

2 Answers 2

4

PowerShell does not normally throw an exception when there is an error. Instead it writes a record to the error stream, which you can redirect. To force it to throw there are two options. One is to set the global error preference to stop:

$ErrorActionPreference = "Stop"

The other is to set the ErrorAction parameter to stop. This is supported for cmdlets that accept the so-called common parameters, which Remove-Item does:

Remove-Item "c:\test\new text document.txt" -force -EA "Stop"

To redirect the error stream you use the code 2:

Remove-Item "c:\test\new text document.txt" -Force 2>> $LogFile

That would append the error to the log file. The record isn't written to the error stream if your option is "Stop" however. It is simply included in the exception that is thrown.

Sign up to request clarification or add additional context in comments.

1 Comment

It's not that PowerShell doesn't normally throw exceptions, but that it distinguishes between two types of errors: terminating and non-terminating errors. The former throw while the latter don't. By setting -ErrorAction or $ErrorActionPreference to Stop you instruct the interpreter to treat all errors as terminating errors.
2

Add the ErrorAction switch to your Remove-Item command:

Remove-Item "c:\test\new text document.txt" -force -ErrorAction Stop

There's quite a good treatment on error handling here:

http://blogs.msdn.com/b/kebab/archive/2013/06/09/an-introduction-to-error-handling-in-powershell.aspx

1 Comment

Link is now dead. Travis Plunk has an archive of the blog post: ghost.ez13.net/an-introduction-to-error-handling-in-powershell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.