3

I've recently broken into some of the subtler nuances of PowerShell, and noticed something I cannot avoid involving the return of a new line at the start of a string using this mundane function...

Function Why() { "" return "Well I tried." } 

This returns "\r\nWell I tried".

Write-Host "Starting test." $theBigQuestion= Why Write-Host $theBigQuestion Write-Host "Ending test." 

This will output the following:

Starting test. Well I tried. Well I tried. Ending test. 

Now, this appears PowerShell is concatenating one output with another. But... why? What makes it think that I wanted the blank line to be part of the return statement? I (perhaps erroneously) like to use lines like this as shorthand, or to examine variables more closely for debugging purposes.

Related: Function return value in PowerShell

6
  • what is the "" doing in the function? that is what echoing the blank line \r\n Commented Jul 29, 2014 at 16:43
  • @bansi "" was originally echoing a blank line to the console. It's a bad habit of mine. I know the "what", but I'm trying to figure out the "why". Commented Jul 29, 2014 at 16:47
  • Which version of powershell is this? I do not see a blank line or "Well I tried." printed twice in 4.0. Commented Jul 29, 2014 at 16:57
  • @mikez This is PowerShell 2.0... which may be causing the problem. Commented Jul 29, 2014 at 17:00
  • 1
    get-help about_return. Anything that is not captured in a function will get returned. use write-host and you won't have this problem Commented Jul 29, 2014 at 17:40

2 Answers 2

7

This function:

Function Why() { "" return "Well I tried." } 

Is returning an array of two strings. The first string is an empty string and the second is "Well I tried.". When PowerShell displays an array of string it puts each string on a newline.

25> $r = why 26> $r.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array 27> $r[0].Length 0 28> $r[1] Well I tried. 
Sign up to request clarification or add additional context in comments.

1 Comment

...and here I was thinking it was returning a string the entire time. Derp.... thank you.
0

If you just want to have "Well I tried" to return, you can also use Out-Null or assign the unwanted return value to $null

Function Why() { Out-Null "" return "Well I tried." } 

or

Function Why() { $null = "" return "Well I tried." } 

or

Function Why() { "" > $null return "Well I tried." } 

Comments