Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active May 18, 2018 17:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnetikonline/b38c2e7339c2090fdafa72dc41e68185 to your computer and use it in GitHub Desktop.
Save magnetikonline/b38c2e7339c2090fdafa72dc41e68185 to your computer and use it in GitHub Desktop.
PowerShell calling a function quirk.

PowerShell calling a function quirk

Something that trips me up often and a handy note to others. When calling a PowerShell function and storing the returned value, all output and the return value will be stored.

Example

Some code:

function myFunction() {

	Write-Output -InputObject "Hello there"
	return "return value"
}


Write-Output -InputObject "Calling function myFunction()"
myFunction

Write-Output -InputObject ""

Write-Output -InputObject "Calling function myFunction(), store result"
$returned = myFunction

Write-Output -InputObject ""
Write-Output -InputObject "Output of `$returned"
Write-Output -InputObject $returned

Running

PS Z:\> ./quirk.ps1
Calling function myFunction()
Hello there
return value

Calling function myFunction(), store result

Output of $returned
Hello there
return value
PS Z:\>

As you can see the value of myFunction() stored in $returned contains both:

  • The output of the Write-Output call (Hello there) and...
  • The actual value returned (return value).

Easiest way to avoid if using Write-Output calls for debugging in functions, replace with Write-Verbose calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment