← All Articles

PowerShell is not C#

Jan. 3, 2017

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

What is happening here? |% { ... } is a script block. 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
← All Articles