Tigraine

Daniel Hoelbling-Inzko talks about programming

Powershell Functions are a different kind of beast!

Posted by Daniel Hölbling on September 22, 2010

When you look at functions in C style language there are some things always true:

  1. Return always terminates the function
  2. Return <something> returns a value/reference to the thing you return

Guess what: Powershell is no C style language! It may look like one with all the curly braces and the $ (reminding you of PHP) before variables. But it is no C language, rather it is a shell.. And shells seem to be working differently.

Care to hazard a guess what this will output?

function Test
{
    $a = "Hello World"
    "Sorry World is not available"
    return $a
}

$output = Test
Write-Host $output

If you’d expect it to return “Hello World” you are wrong. Actually the return value of the function Test is an array of 2 System.String:

Sorry World is not available Hello World

Madness I know. But fact is that all things that get written to the “output” (like Write-Host) inside a function is part of the function output. You don’t need to use return.

This also means if you run commands like –match inside a function

$v –match “regex”

–match will output true or false to the output. And thus your method output will include a True somewhere you don’t need it. Like this:

function Test
{
    $a = "Hello World"
    $a -match "World"
    return $matches[0]
}

$output = Test
Write-Host $output

Will output: True World

You can avoid this behavior through redirecting the “output” to $null or by adding the [void] attribute like this:

function Test
{
    $a = "Hello World"
    $a -match "World" > $null
    return $matches[0]
}

$output = Test
Write-Host $output

I never thought I’d have to revisit the workings of a return statement again, but obviously there is always the possibility for someone to come along and teach me something new. This person btw is Keith Hill who wrote an excellent article on Powershell Output that sheds some light on this topic and does a far better job at explaining it than I can possibly do.

Filed under programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more