Invoke-Expression - write output to console but dont return it from function

1.6k Views Asked by At

I want to call Invoke-Expression inside a function and print the output of the command to the console but don't return it from the function since I want to return a specific value from it.

function Foo {
    $command = 'mvn clean package "-Dmaven.test.skip"'
    Invoke-Expression -Command $command | Write-Host

    $result = 'computed return value'
    return $result
}


$fooResult = Foo
Write-Output "fooResult is: ${fooResult}"

This works, but I want to avoid using the evil Write-Host function, so I tried Write-Information instead. But I it seems you can't pipe the output of the Invoke-Expression to Write-Information. When I simply replace Write-Host with Write-Information it behaves like the -MessageData Parameter is not provided (similar when explicitly stating -MessageData).

Is there a way to write the output of Invoke-Expression to the console, but avoid returning it from the function without using Write-Host?

2

There are 2 best solutions below

6
On

You try with OutVariable

function Foo {
    $command = 'mvn clean package "-Dmaven.test.skip"'
    Invoke-Expression -Command $command -OutVariable OutputData | Out-Null

    Write-Information -MessageData "INFO: $OutputData" -INFA "Continue"
    return "something else"
}
1
On

Output to the screen is the Powershell default unless you tell it to do otherwise. So, Write-* is almost moot, in many cases. Yet, folks have their reasons for using Write-* cmdlets.

There are several ways to write to the screen and even save to a variable and write to the screen at the same time.

  • variable squeezing
  • Out-String
  • Out-Host
  • Tee-Object

The aforementioned and more have been regularly covered.

Example web hits:

https://ridicurious.com/2017/06/30/3-ways-to-store-display-results-infrom-a-powershell-variable-at-the-same-time

https://mikefrobbins.com/2014/03/28/powershell-output-the-result-of-a-command-and-assign-it-to-a-variable-in-one-line

Get-Process a* -OutVariable process
($process = Get-Process a*)
Get-Process a* | Tee-Object -Variable p

Your post can even be seen as a duplicate of this similar use case:

Invoke-expression output on Screen and in a variable

Invoke-Expression $var -OutVariable | Tee-Object -Variable out 

Invoke-Expression $var | Tee-Object C:\Path\To\File.txt

Running executables from Powershell is also a well-documented use case. See this from MS.

• PowerShell: Running Executables

https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx