« Screen Capture and Recording | Main | Interlude: Giant Steps Animated by Michal Levy »
Thursday
Apr042013

Two tips for C# Developers Trying to Learn PowerShell (Set-StrictMode and ErrorActionPreference)

Summary

Let's get right to it. If you are coming to POwerShell via C#, you'll want to start off with these two lines at the top of your script.  

Set-StrictMode -Version 2
$ErrorActionPreference = "Stop"

 

Now, let's understand why.

 

Set-StrictMode -Version 2

In C# you will be used to the following code failing

    void foo()
    {
        Console.WriteLine( somevar );
    }

The reason it should fail is simple: somevar hasn't been defined anywhere.

The nearest equivalent in PowerShell does not fail!

    Write-Host $somevar

By default, undefined variables are treated as null. As you can imagine this leads to some hard-to-find bugs. But there is good news. You can force PowerShell to treat this as an error by using the following cmdlet.

    Set-StrictMode -Version 2

Now, if you run the script below;

    Set-StrictMode -Version 2
    Write-Hos $somevar

PowerShell will complain with a message saying that “The variable $somevar cannot be retrieved because it has not been set”

In general, I always use Set-StrictMode –Version 2 for my scripts.

 

$ErrorActionPreference = "Stop"

How many times will the following loop in C# get run?

    for (int i=0;i<9;i++)
    {
        Console.WriteLine( 1 / 0 ); // that’s right: divide one by zero
    }

In the C# world we know that we’ll enter the loop only once. Execution will be halted because of the divide-by-zero.

But equivalent loop in Powershell gets run 10 times! Because by default errors don’t cause PowerShell scripts to terminate.

    foreach ($I in 0..9)
    {
        Write-Host 1/0
    }

What will happen in this loop is that PowerShell will attempt the loop all ten times!

This behavior can be quite useful in some scripts, but will certainly be surprising for most developers.

Fortunately we can tell PowerShell to stop by using $ErrorActionPreference. Just set its value to “Stop”

    $ErrorActionPreference = "Stop"

In the script below, the loop and the script will halt on the first divide-by-zero.

    $ErrorActionPreference = "Stop"
    foreach ($I in 0..9)
    {
        Write-Host 1/0
    }

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>