17.5. Trap Statement

The trap statement allows you to take control of what happens when an error occurs.

NOTE

Don't attempt to use the trap statement to trap nonterminating errors. It doesn't work for those.

The script TrappedForLoop.ps1 writes a custom message to the console when an exception occurs and specifies that execution is to continue:

for ($i = 5;  $i -gt −2; $i--)
{
trap {write-host "This is a custom error message.";continue}
write-host '$i'"=$i"
1/$i
write-host '$?'"=$?"
}
write-host "This statement comes after the for loop."

As the value of $i is decremented, eventually the statement 1/$i becomes 1/0, which causes an error. The error is trapped and the custom error message is displayed, as you can see in Figure 17-16. Even when the $ErrorActionPreference is set to Stop, execution of the for loop continues, as does execution of statements following the for loop.

Figure 17.16. Figure 17-16

The following script, BlockedWrite.ps1, writes sample text to four files (using redirection), sets the file Test3.txt to read-only, then attempts to append further text to Test3.txt.

Trap {write-host "You can't write to a read-only file."}
"This is file 1" > Test1.txt
"This is file 2" > Test2.txt
"This is file 3" > Test3.txt
"This is file 4" > Test4.txt
attrib +r Test3.txt
"Add to file 3" >> Test3.txt

Execute the script using the following command:

.\BlockedWrite.ps1

As you can see ...

Get Professional Windows® PowerShell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.