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

Community
  • 1
  • 1
  • what is the `""` doing in the function? that is what echoing the blank line `\r\n` – bansi Jul 29 '14 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". –  Jul 29 '14 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. – Mike Zboray Jul 29 '14 at 16:57
  • @mikez This is PowerShell 2.0... which may be causing the problem. –  Jul 29 '14 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 – Cole9350 Jul 29 '14 at 17:40
  • I tried this on version 2.0 as well. I see the same output as 4.0. – Mike Zboray Jul 29 '14 at 17:44

2 Answers2

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.
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • ...and here I was thinking it was returning a string the entire time. Derp.... thank you. –  Jul 29 '14 at 17:44
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."
}
letthefireflieslive
  • 11,493
  • 11
  • 37
  • 61