How do I avoid getting data printed to stdout in my return value?
Here are a few different approaches for handling this:
capture the output of the .cmd script:
$output = & external.cmd # saves foo to $output so it isn't returned from the function
redirect the output to null (throw it away)
& external.cmd | Out-Null # throws stdout away
redirect it to a file
& external.cmd | Out-File filename.txt
ignore it in the caller by skipping it in the array of objects that's returned from the function
$val = aecho $val[1] #prints second object returned from function a (foo is object 1... $val[0])
In PowerShell, any output value your code does not capture is returned the caller (including stdout, stderr, etc). So you have to capture or pipe it to something that doesn't return a value, or you'll end up with an object[] as your return value from the function.
The return
keyword is really just for clarity and immediate exit of a script block in PowerShell. Something like this would even work (not verbatim but just to give you the idea):
function foo(){ "a" "b" "c"}PS> $bar = fooPS> $bar.gettype()System.Object[]PS> $barabcfunction foobar(){ "a" return "b" "c"}PS> $myVar = foobarPS> $myVarab
I generally prefer to use one of the following two techniques which, in my opinion, make the code more readable:
Cast an expression to void in order to suppress the return value:
[void] (expression)
Assign the output value to the $null variable:
$null = expression
For example:
function foo{ # do some work return "success"}function bar{ [void] (foo) # no output $null = foo # no output return "bar"}bar # outputs bar
If you want the output from the command to still print to the powershell command line, you can do a variant of the accepted answer:
& external.cmd | Out-Host