PowerShell V1 doesn’t like to exit assignment functions

I was working on a fancy backup script for Perforce written in Powershell and I’ve definitely come across a bug in PowerShell V1.  Take a look at this:

function Usage()
{
	write-host "Hey fool, you need to pass 1 paramter to this utility!"
	exit 1
}
 
if ($args.Count -ne 1)
{
	Usage
}
write-host "Doing stuff..."

So that little snippet, if run without a parameter, will tell you you’re a fool and never tell you it’s doing stuff. I use exit to abort the entire script.  Works as expected.  Now take a look at this:

function GetMyWidget()
{
	# Pretend I couldnt find my widget
	if ($foundWidget -ne $true)
	{
		write-host "Ooops, something went wrong and I want to exit this script!"
		exit 1
	}
	return $widget
}
$w = GetMyWidget
write-Host "Whatever you do, don't print this!"

I expect the above snippet to print out Ooops… and that’s it. Unfortunately this is what it prints:

PS H:\temp> H:\temp\test.ps1
Ooops, something went wrong and I want to exit this script!
The ‘=’ operator failed: System error..
At H:\temp\test.ps1:11 char:5
+ $w =  <<<< GetMyWidget

Whatever you do, don’t print this!
PS H:\temp>

Execute the same code in Powershell V2 CTP3, no error, and it NEVER prints “Whatever you do, don’t print this!”.   The difference between the snippets is I’m assigning a variable to the return value of my function that contains an exit.  Note both environments $errorActionPreference is continue.

That is pretty annoying.  The workaround is to put $script:errorActionPreference = “Stop” before you exit statement, or to make sure that is the preference somewhere.

This entry was posted in General and tagged . Bookmark the permalink.

One Response to PowerShell V1 doesn’t like to exit assignment functions

  1. Tom H says:

    I just tried adding the workaround code, immediately before my Exit statement, and I still get the same error. Saddenz. 🙁

Leave a Reply

Your email address will not be published. Required fields are marked *