Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell redirect std error to variable

I would like to invoke an arbitrary expression and redirect std error to a variable without redirection to a file.

For example, in Powershell it is possible to redirect standard error using 2> operator. Using a temporary file, I can easily get what I want:

#$expr = "1/0"                          # with std error
#$expr = "2+2"                          # without stderror
#$expr = "Get-Service invalidsvc"       # with stderror
$expr = "try { throw '111' } catch { }" # without std error
$ans = Invoke-Expression $expr -ErrorVariable ev 2> C:\log\stderr.txt
if(cat C:\log\stderr){
    Write-Host "Error $ev"    
}

How can I do the same, but without creation of a temporal output file?

Wrong solutions:

  1. Using -ErrorVariable switch. Counter example:

    Invoke-Expression $expr -ErrorVariable ev 2> C:\aaa\file1.txt $expr = "try { throw '111' } catch { }" Write-Host "Error $ev" # will output error, but std error is empty

  2. $LASTEXITCODE and $? check. Counter example:

    Get-Service invalidservice

$lastexitcode is equal to 0, $? is equal to True, but std error is not empty

The idea is simple: save the "red" (std error) text in Powershell console in a variable. The command I receive is an arbitrary string. Examples:

  1. When I write "try { throw '111' } catch { }" in Powershell console there will be no red (error) text in PS console (despite the fact $error is not empty). So if I invoke that expression in my code I get no error saved in some variable.

  2. When I write "Get-Service notexistingservice", or "1/0", or "Write-Error 111" there will red (error) text and non-null $error. So if I invoke that expression in my code I would like to get error saved in some variable.

like image 766
2xMax Avatar asked Aug 05 '26 00:08

2xMax


1 Answers

Save standard output and standard error to separate variables. It won't work without the dollar sign (from Windows Powershell in Action).

$err = $( $output = get-childitem foo3 ) 2>&1
like image 151
js2010 Avatar answered Aug 07 '26 00:08

js2010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!