Skip to main content

PowerShell is not C#

Submitted by admin on Tue, 01/03/2017 - 22:09

PowerShell may be based on .NET, but it most certainly is not C#. There are quite a few differences between these two languages that are not immediately apparent and can lead to some weird issues. I'm going to give a few examples in this article.

1. Return Behavior

The return keyword in C# always terminates the execution of the current method. I initially made the assumption that the same applies to PowerShell, but that isn't entirely true.

From the documentation:

Exits the current scope, which can be a function, script, or script block.

So in PowerShell it's not just methods. The problem is script blocks are not immediately obvious, take the following function for example:

function Get-ArrayContainsEvenNumber([int[]] $numbersArray)
{
    $numbersArray |% {
        if ($_ % 2 -eq 0) {
            return $true
        }
    }
    return $false   
}

# When using the function..
Get-ArrayContainsEvenNumber 3,5,6
True
False

What is happening here? |% { ... } is a ScriptBlock. So the return statement here applies only the loop that iterates over the numbers, not the method itself. The example would be working fine with a foreach statement instead.

2. Explicitly defined strings can't be $null

Take the following example:

[string] $a = "whatever.."
$a = $null

# So it should be $null, right?
if ($a -eq $null) {
    "String is null!"
} else {
    "String is not null!"
}

It returns "String is not null!". Why? Because PowerShell automatically converts the null into an empty string, if the variable is explicitly defined as a string. So, remember to check for an empty string instead. Or alternatively:

$a = [NullString]::Value
$a -eq $null
True

 

I'll be adding new stuff as I come across it.

Tags