PowerShell Write-Output inside "if" does not output anything
You can achieve desired results by replacing Write-Output
with Write-Host
. This is suitable only if your main concern is to produce output in the console as Write-Host
does not go to stdout stream.
You can read more about difference between the 2 cmdlets in this SO thread :Which should I use: "Write-Host", "Write-Output", or "[console]::WriteLine"?
PowerShell functions are not like their traditional language counterparts: they can output multiple things. When you're using Write-Output
, you are sending things down the pipeline, so func1()
will return both a String and a Boolean. If you try this:
$return_values = func1;
$return_values | Get-Member
You will see that you get both System.String
and System.Boolean
objects in $return_values
. Indeed the 'return' statement is more like an 'exit' or 'break' in traditional languages: it marks an exit point, but the function will actually return with whatever was already outputted (+ the optional return argument).
The quick fix to the issue is to change Write-Output
to Write-Host
, though they do slightly different things.