PowerShell Streaming Output - powershell

I'd like to capture some streaming output in PowerShell. For example
cmd /c "echo hi && foo"
This command should print hi and then bomb. I know that I can use -ErrorVariable:
Invoke-Command { cmd /c "echo hi && foo" } -ErrorVariable ev
however there is an issue: in the case of long running commands, I want to stream the output, not capture it and only get the stderr/stdout output at the end of the command
Ideally, I'd like to be able to split stderr and stdout and pipe to two different streams - and pipe the stdout back to the caller, but be prepared to throw stderr in the event of an error. Something like
$stdErr
Invoke-Command "cmd" "/c `"echo hi && foo`"" `
-OutStream (Get-Command Write-Output) `
-ErrorAction {
$stdErr += "`n$_"
Write-Error $_
}
if ($lastexitcode -ne 0) { throw $stdErr}
the closest I can get is using piping, but that doesn't let me discriminate between stdout and stderr so I end up throwing the entire output stream
function Invoke-Cmd {
<#
.SYNOPSIS
Executes a command using cmd /c, throws on errors.
#>
param([string]$Cmd)
)
$out = New-Object System.Text.StringBuilder
# I need the 2>&1 to capture stderr at all
cmd /c $Cmd '2>&1' |% {
$out.AppendLine($_) | Out-Null
$_
}
if ($lastexitcode -ne 0) {
# I really just want to include the error stream here
throw "An error occurred running the command:`n$($out.ToString())"
}
}
Common usage:
Invoke-Cmd "GitVersion.exe" | ConvertFrom-Json
Note that an analogous version that just uses a ScriptBlock (and checking the output stream for [ErrorRecord]s isn't acceptable because there are many programs that "don't like" being executed directly from the PowerShell process
The .NET System.Diagnostics.Process API lets me do this...but I can't stream output from inside the stream handlers (because of the threading and blocking - though I guess I could use a while loop and stream/clear the collected output as it comes in)

- The behavior described applies to running PowerShell in regular console/terminal windows with no remoting involved. With remoting and in the ISE, the behavior is different as of PSv5.1 - see bottom.
- The 2>$null behavior that Burt's answer relies on - 2>$null secretly still writing to PowerShell's error stream and therefore, with $ErrorActionPreference Stop in effect, aborting the script as soon as an external utility writes anything to stderr - has been classified as a bug and is likely to go away.
When PowerShell invokes an external utility such as cmd, its stderr output is passed straight through by default. That is, stderr output prints straight to the console, without being included in captured output (whether by assigning to a variable or redirecting to a file).
While you can use 2>&1 as part of the cmd command line, you won't be able to distinguish between stdout and stderr output in PowerShell.
By contrast, if you use 2>&1 as a PowerShell redirection, you can filter the success stream based on the input objects' type:
A [string] instance is a stdout line
A [System.Management.Automation.ErrorRecord] instance is a stderr line.
The following function, Invoke-CommandLine, takes advantage of this:
Note that the cmd /c part isn't built in, so you would invoke it as follows, for instance:
Invoke-CommandLine 'cmd /c "echo hi && foo"'
There is no fundamental difference between passing invocation of a cmd command line and direct invocation of an external utility such as git.exe, but do note that only invocation via cmd allows use of multiple commands via operators &, &&, and ||, and that only cmd interprets %...%-style environment-variable references, unless you use --%, the stop-parsing symbol.
Invoke-CommandLine outputs both stdout and stderr line as they're being received, so you can use the function in a pipeline.
As written, stderr lines are written to PowerShell's error stream using Write-Error as they're being received, with a single, generic exception being thrown after the external command terminates, should it report a nonzero $LASTEXITCODE.
It's easy to adapt the function:
to take action once the first stderr line is received.
to collect all stderr lines in a single variable
and/or, after termination, to take action if any stderr input was received, even with $LASTEXITCODE reporting 0.
Invoke-CommandLine uses Invoke-Expression, so the usual caveat applies: be sure you know what command line you're passing, because it will be executed as-is, no matter what it contains.
function Invoke-CommandLine {
<#
.SYNOPSIS
Executes an external utility with stderr output sent to PowerShell's error '
stream, and an exception thrown if the utility reports a nonzero exit code.
#>
param([parameter(Mandatory)][string] $CommandLine)
# Note that using . { ... } is required around the Invoke-Expression
# call to ensure that the 2>&1 redirection works as intended.
. { Invoke-Expression $CommandLine } 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) { # stderr line
Write-Error $_ # send stderr line to PowerShell's error stream
} else { # stdout line
$_ # pass stdout line through
}
}
# If the command line signaled failure, throw an exception.
if ($LASTEXITCODE) {
Throw "Command failed with exit code ${LASTEXITCODE}: $CommandLine"
}
}
Optional reading: how calls to external utilities fit into PowerShell's error handling
Current as of: Windows PowerShell v5.1, PowerShell Core v6-beta.2
The value of preference variable $ErrorActionPreference only controls the reaction to errors and .NET exceptions that occur in PowerShell cmdlet/function calls or expressions.
Try / Catch is for catching PowerShell's terminating errors and .NET exceptions.
In a regular console window with no remoting involved, external utilities such as cmd currently never generate either error - all they do is report an exit code, which PowerShell reflects in automatic variable $LASTEXITCODE, and automatic variable $? reflects $False if the exit code is nonzero.
Note: The fact that the behavior differs fundamentally in hosts other than the console host - which includes the Windows ISE and when remoting is involved - is problematic: There, calls to external utilities result in stderr output treated as if non-terminating errors had been reported; specifically:
Every stderr output line is output as an error record and also recorded in the automatic $Error collection.
In addition to $? being set to $false with a nonzero exit code, the presence of any stderr output also sets it to $False.
This behavior is problematic, as stderr output by itself does not necessarily indicate an error - only a nonzero exit code does.
Burt has created an issue in the PowerShell GitHub repository to discuss this inconsistency.
By default, stderr output generated by an external utility is passed straight through to the console - they are not captured by PowerShell variable assignments or (success-stream) output redirections.
As discussed above, this can be changed:
2>&1 as part of a command line passed to cmd sends stdout and stderr combined to PowerShell's success stream, as strings, with no way to distinguish between whether a given line was a stdout or stderr line.
2>&1 as a PowerShell redirection sends stderr lines to PowerShell's success stream too, but you can distinguish between stdout- and stderr-originated lines by their DATA TYPE: a [string]-typed line is a stdout-originated line, whereas a [System.Management.Automation.ErrorRecord]-typed line is a stderr-originated one.

Note: updated sample below should now work across PowerShell hosts. GitHub issue Inconsistent handling of native command stderr has been opened to track the discrepancy in previous example. Note however that as it depends on undocumented behavior, the behavior may change in the future. Take this into consideration before using it in a solution that must be durable.
You are on the right track with using pipes, you probably don't need Invoke-Command, almost ever. Powershell DOES distinguish between stdout and stderr. Try this for example:
cmd /c "echo hi && foo" | set-variable output
The stdout is piped on to set-variable, while std error still appears on your screen. If you want to hide and capture the stderr output, try this:
cmd /c "echo hi && foo" 2>$null | set-variable output
The 2>$null part is an undocumented trick that results in the error output getting appended to the PowerShell $Error variable as an ErrorRecord.
Here's an example that displays stdout, while trapping stderr with an catch block:
function test-cmd {
[CmdletBinding()]
param()
$ErrorActionPreference = "stop"
try {
cmd /c foo 2>$null
} catch {
$errorMessage = $_.TargetObject
Write-warning "`"cmd /c foo`" stderr: $errorMessage"
Format-list -InputObject $_ -Force | Out-String | Write-Debug
}
}
test-cmd
Generates the message:
WARNING: "cmd /c foo" stderr: 'foo' is not recognized as an internal or external command
If you invoke with debug output enabled, you'll alsow see the details of the thrown ErrorRecord:
DEBUG:
Exception : System.Management.Automation.RemoteException: 'foo' is not recognized as an internal or external command,
TargetObject : 'foo' is not recognized as an internal or external command,
CategoryInfo : NotSpecified: ('foo' is not re...ternal command,:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at test-cmd, <No file>: line 7
at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails :
Setting $ErrorActionPreference="stop" causes PowerShell to throw an exception when the child process writes to stderr, which sounds like it's the core of what you want. This 2>$null trick makes the cmdlet and external command behavior very similar.

Related

Why does PowerShell interpret kind/kubectl STDOUT as STDERR and How to Prevent it?

We are moving our DevOps pipelines to a new cluster and while at it, we bumped into a weird behavior when calling kind with PowerShell. This applies to kubectl also.
The below should be taken only as a repro, not a real world application. In other words, I'm not looking to fix the below code but I am searching for an explanation why the error happens:
curl.exe -Lo kind-windows-amd64.exe https://kind.sigs.k8s.io/dl/v0.10.0/kind-windows-amd64
Move-Item .\kind-windows-amd64.exe c:\temp\kind.exe -Force
$job = Start-Job -ScriptBlock { iex "$args" } -ArgumentList c:\temp\kind.exe, get, clusters
$job | Receive-Job -Wait -AutoRemoveJob
Now, if I directly execute the c:\temp\kind.exe get clusters command in the PowerShell window, the error won't happen:
In other words, why does PowerShell (any version) consider the STDOUT of kind/kubectl as STDERR? And how can I prevent this from happening?
There must be an environmental factor to it as the same exact code runs fine in one system while on another it throws an error...
tl;dr
kind outputs its status messages to stderr, which in the context of PowerShell jobs surface via PowerShell's error output stream, which makes them print in red (and susceptible to $ErrorActionPreference = 'Stop' and -ErrorAction Stop).
Either:
Silence stderr: Use 2>$null as a general mechanism or, as David Kruk suggests, use a program-specific option to achieve the same effect, which in the case of kind is -q (--quiet)
Re-route stderr output through PowerShell's success output stream, merged with stdout output, using *>&1.
Caveat: The original output sequencing between stdout and stderr lines is not necessarily maintained on output.
Also, if you want to know whether the external program reported failure or success, you need to include the value of the automatic $LASTEXITCODE variable, which contains the most recently executed external program's process exit code, in the job's output (the exit code is the only reliably success/failure indicator - not the presence or absence of stderr output).
A simplified example with *>&1 (for Windows; on Unix-like platforms, replace cmd and /c with sh and -c):
$job = Start-Job -ScriptBlock {
param($exe)
& $exe $args *>&1
$LASTEXITCODE # Also output the process exit code.
} -ArgumentList cmd, /c, 'echo data1; echo status >&2; echo data2'
$job | Receive-Job -Wait -AutoRemoveJob
As many utilities do, kind apparently reports status messages via stderr.
Given that stdout is for data, it makes sense to use the only other available output stream, stderr, for anything that isn't data, so as to prevent pollution of the data output. The upshot is that stderr output doesn't necessarily indicate actual errors (success vs. failure should solely be inferred from an external program's process exit code).
PowerShell (for its own commands only) commendably has a more diverse system of output streams, documented in the conceptual about_Redirection help topic, allowing you to report status messages via Write-Verbose, for instance.
PowerShell maps an external program's output streams to its own streams as follows:
Stdout output:
Stdout output is mapped to PowerShell's success output stream (the stream with number 1, analogous to how stdout can be referred to in cmd.exe and POSIX-compatible shells), allowing it to be captured in a variable ($output = ...) or redirected to a file (> output.txt) or sent through the pipeline to another command.
Stderr output:
In local, foreground processing in a console (terminal), stderr is by default not mapped at all, and is passed through to the display (not colored in red) - unless a 2> redirection is used, which allows you to suppress stderr output (2>$null) or to send it to a file (2>errs.txt)
This is appropriate, because PowerShell cannot and should not assume that stderr output represents actual errors, whereas PowerShell's error stream is meant to be used for errors exclusively.
Unfortunately, as of PowerShell 7.2, in the context of PowerShell jobs (created with Start-Job or Start-ThreadJob) and remoting (e.g., in Invoke-Command -ComputerName ... calls), stderr output is mapped to PowerShell's error stream (the stream with number 2, analogous to how stdout can be referred to in cmd.exe and POSIX-compatible shells).
Caveat: This means that if $ErrorActionPreference = 'Stop' is in effect or -ErrorAction Stop is passed to Receive-Job or Invoke-Command, for instance, any stderr output from external programs will trigger a script-terminating error - even with stderr output comprising status messages only. Due to a bug in PowerShell 7.1 and below this can also happen in local, foreground invocation if a 2> redirection is used.
The upshot:
To silence stderr output, apply 2>$null - either at the source (inside the job or remote command), or on the receiving end.
To route stderr output (all streams) via the success output stream / stdout, i.e. to merge all streams, use *>&1
To prevent the stderr lines from printing in red (when originating from jobs or remote commands), apply this redirection at the source - which also guards against side effects from $ErrorActionPreference = 'Stop' / -ErrorAction Stop on the caller side.
Note: If you merge all streams with *>&1, the order in which stdout and stderr lines are output is not guaranteed to reflect the original output order, as of PowerShell 7.2.
If needed, PowerShell still allows you to later separate the output lines based on whether they originated from stdout or stderr - see this answer.

Powershell: Redirecting stderr causes an exception [duplicate]

Why does PowerShell show the surprising behaviour in the second example below?
First, an example of sane behaviour:
PS C:\> & cmd /c "echo Hello from standard error 1>&2"; echo "`$LastExitCode=$LastExitCode and `$?=$?"
Hello from standard error
$LastExitCode=0 and $?=True
No surprises. I print a message to standard error (using cmd's echo). I inspect the variables $? and $LastExitCode. They equal to True and 0 respectively, as expected.
However, if I ask PowerShell to redirect standard error to standard output over the first command, I get a NativeCommandError:
PS C:\> & cmd /c "echo Hello from standard error 1>&2" 2>&1; echo "`$LastExitCode=$LastExitCode and `$?=$?"
cmd.exe : Hello from standard error
At line:1 char:4
+ cmd <<<< /c "echo Hello from standard error 1>&2" 2>&1; echo "`$LastExitCode=$LastExitCode and `$?=$?"
+ CategoryInfo : NotSpecified: (Hello from standard error :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
$LastExitCode=0 and $?=False
My first question, why the NativeCommandError?
Secondly, why is $? False when cmd ran successfully and $LastExitCode is 0? PowerShell's documentation about automatic variables doesn't explicitly define $?. I always supposed it is True if and only if $LastExitCode is 0, but my example contradicts that.
Here's how I came across this behaviour in the real-world (simplified). It really is FUBAR. I was calling one PowerShell script from another. The inner script:
cmd /c "echo Hello from standard error 1>&2"
if (! $?)
{
echo "Job failed. Sending email.."
exit 1
}
# Do something else
Running this simply as .\job.ps1, it works fine, and no email is sent. However, I was calling it from another PowerShell script, logging to a file .\job.ps1 2>&1 > log.txt. In this case, an email is sent! What you do outside the script with the error stream affects the internal behaviour of the script. Observing a phenomenon changes the outcome. This feels like quantum physics rather than scripting!
[Interestingly: .\job.ps1 2>&1 may or not blow up depending on where you run it]
(I am using PowerShell v2.)
The '$?' variable is documented in about_Automatic_Variables:
$?
Contains the execution status of the last operation
This is referring to the most recent PowerShell operation, as opposed to the last external command, which is what you get in $LastExitCode.
In your example, $LastExitCode is 0, because the last external command was cmd, which was successful in echoing some text. But the 2>&1 causes messages to stderr to be converted to error records in the output stream, which tells PowerShell that there was an error during the last operation, causing $? to be False.
To illustrate this a bit more, consider this:
> java -jar foo; $?; $LastExitCode
Unable to access jarfile foo
False
1
$LastExitCode is 1, because that was the exit code of java.exe. $? is False, because the very last thing the shell did failed.
But if all I do is switch them around:
> java -jar foo; $LastExitCode; $?
Unable to access jarfile foo
1
True
... then $? is True, because the last thing the shell did was print $LastExitCode to the host, which was successful.
Finally:
> &{ java -jar foo }; $?; $LastExitCode
Unable to access jarfile foo
True
1
...which seems a bit counter-intuitive, but $? is True now, because the execution of the script block was successful, even if the command run inside of it was not.
Returning to the 2>&1 redirect.... that causes an error record to go in the output stream, which is what gives that long-winded blob about the NativeCommandError. The shell is dumping the whole error record.
This can be especially annoying when all you want to do is pipe stderr and stdout together so they can be combined in a log file or something. Who wants PowerShell butting in to their log file??? If I do ant build 2>&1 >build.log, then any errors that go to stderr have PowerShell's nosey $0.02 tacked on, instead of getting clean error messages in my log file.
But, the output stream is not a text stream! Redirects are just another syntax for the object pipeline. The error records are objects, so all you have to do is convert the objects on that stream to strings before redirecting:
From:
> cmd /c "echo Hello from standard error 1>&2" 2>&1
cmd.exe : Hello from standard error
At line:1 char:4
+ cmd &2" 2>&1
+ CategoryInfo : NotSpecified: (Hello from standard error :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
To:
> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" }
Hello from standard error
...and with a redirect to a file:
> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" } | tee out.txt
Hello from standard error
...or just:
> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" } >out.txt
This bug is an unforeseen consequence of PowerShell's prescriptive design for error handling, so most likely it will never be fixed. If your script plays only with other PowerShell scripts, you're safe. However if your script interacts with applications from the big wide world, this bug may bite.
PS> nslookup microsoft.com 2>&1 ; echo $?
False
Gotcha! Still, after some painful scratching, you'll never forget the lesson.
Use ($LastExitCode -eq 0) instead of $?
(Note: This is mostly speculation; I rarely use many native commands in PowerShell and others probably know more about PowerShell internals than me)
I guess you found a discrepancy in the PowerShell console host.
If PowerShell picks up stuff on the standard error stream it will assume an error and throw a NativeCommandError.
PowerShell can only pick this up if it monitors the standard error stream.
PowerShell ISE has to monitor it, because it is no console application and thus a native console application has no console to write to. This is why in the PowerShell ISE this fails regardless of the 2>&1 redirection operator.
The console host will monitor the standard error stream if you use the 2>&1 redirection operator because output on the standard error stream has to be redirected and thus read.
My guess here is that the console PowerShell host is lazy and just hands native console commands the console if it doesn't need to do any processing on their output.
I would really believe this to be a bug, because PowerShell behaves differently depending on the host application.
Update: The problems have been fixed in v7.2 - see this answer.
A summary of the problems as of v7.1:
The PowerShell engine still has bugs with respect to 2> redirections applied to external-program calls:
The root cause is that using 2> causes the stderr (standard error) output to be routed via PowerShell's error stream (see about_Redirection), which has the following undesired consequences:
If $ErrorActionPreference = 'Stop' happens to be in effect, using 2> unexpectedly triggers a script-terminating error, i.e. aborts the script (even in the form 2>$null, where the intent is clearly to ignore stderr lines). See GitHub issue #4002.
Workaround: (Temporarily) set $ErrorActionPreference = 'Continue'
Since 2> currently touches the error stream, $?, the automatic success-status variable is invariably set to $False if at least one stderr line was emitted, and then no longer reflects the true success status of the command. See this GitHub issue.
Workaround, as recommended in your answer: only ever use $LASTEXITCODE -eq 0 to test for success after calls to external programs.
With 2>, stderr lines are unexpectedly recorded in the automatic $Error variable (the variable that keeps a log of all errors that occurred in the session) - even if you use 2>$null. See this GitHub issue.
Workaround: Short of keeping track how many error records were added and removing them with $Error.RemoveAt() one by one, there is none.
Generally, unfortunately, some PowerShell hosts by default route stderr output from external programs via PowerShell's error stream, i.e. treat it as error output, which is inappropriate, because many external programs use stderr also for status information, or more generally, for anything that is not data (git being a prime example): Not every stderr line can be assumed to represent an error, and the presence of stderr output does not imply failure.
Affected hosts:
The obsolescent Windows PowerShell ISE and possibly other, older GUI-based IDEs other than Visual Studio Code.
When executing external programs via PowerShell remoting or in a background job (these two invocation mechanisms share the same infrastructure and use the ServerRemoteHost host that ships with PowerShell).
Hosts that DO behave as expected in non-remoting, non-background invocations (they pass stderr lines through to the display and print them normally):
Terminals (consoles), including Windows Terminal.
Visual Studio Code with the PowerShell extension; this cross-platform editor (IDE) is meant to supersede the Windows PowerShell ISE.
This inconsistency across hosts is discussed in this GitHub issue.
For me it was an issue with ErrorActionPreference.
When running from ISE I've set $ErrorActionPreference = "Stop" in the first lines and that was intercepting everything event with *>&1 added as parameters to the call.
So first I had this line:
& $exe $parameters *>&1
Which like I've said didn't work because I had $ErrorActionPreference = "Stop" earlier in file (or it can be set globally in profile for user launching the script).
So I've tried to wrap it in Invoke-Expression to force ErrorAction:
Invoke-Expression -Command "& `"$exe`" $parameters *>&1" -ErrorAction Continue
And this doesn't work either.
So I had to fallback to hack with temporary overriding ErrorActionPreference:
$old_error_action_preference = $ErrorActionPreference
try
{
$ErrorActionPreference = "Continue"
& $exe $parameters *>&1
}
finally
{
$ErrorActionPreference = $old_error_action_preference
}
Which is working for me.
And I've wrapped that into a function:
<#
.SYNOPSIS
Executes native executable in specified directory (if specified)
and optionally overriding global $ErrorActionPreference.
#>
function Start-NativeExecutable
{
[CmdletBinding(SupportsShouldProcess = $true)]
Param
(
[Parameter (Mandatory = $true, Position = 0, ValueFromPipelinebyPropertyName=$True)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[Parameter (Mandatory = $false, Position = 1, ValueFromPipelinebyPropertyName=$True)]
[string] $Parameters,
[Parameter (Mandatory = $false, Position = 2, ValueFromPipelinebyPropertyName=$True)]
[string] $WorkingDirectory,
[Parameter (Mandatory = $false, Position = 3, ValueFromPipelinebyPropertyName=$True)]
[string] $GlobalErrorActionPreference,
[Parameter (Mandatory = $false, Position = 4, ValueFromPipelinebyPropertyName=$True)]
[switch] $RedirectAllOutput
)
if ($WorkingDirectory)
{
$old_work_dir = Resolve-Path .
cd $WorkingDirectory
}
if ($GlobalErrorActionPreference)
{
$old_error_action_preference = $ErrorActionPreference
$ErrorActionPreference = $GlobalErrorActionPreference
}
try
{
Write-Verbose "& $Path $Parameters"
if ($RedirectAllOutput)
{ & $Path $Parameters *>&1 }
else
{ & $Path $Parameters }
}
finally
{
if ($WorkingDirectory)
{ cd $old_work_dir }
if ($GlobalErrorActionPreference)
{ $ErrorActionPreference = $old_error_action_preference }
}
}

Redirect powershell output and errors to console (in real-time) and to a variable

I would like to redirect the output of a command in PowerShell, following these rules:
The command is stored to a variable
Output must be written to the console in real-time (i.e. "ping" results), including errors
Output must be stored to a variable, including errors (real-time is not mandatory here)
Here are my tests, assuming:
$command = "echo:"
to test errors redirection, and:
$command = "ping 127.0.0.1"
to test real-time output.
Output is written in real-time, errors are not redirected at all
Invoke-Expression $command 2>&1 | Tee-Object -Variable out_content
Output is written in real-time, errors are only redirected to the console
Invoke-Expression ($command 2>&1) | Tee-Object -Variable out_content
Invoke-Expression $command | Tee-Object -Variable out_content 2>&1
Output is not written in real-time, errors are correctly redirected to both
(Invoke-Expression $command) 2>&1 | Tee-Object -Variable out_content
Is it possible to get those rules working together?
Some general recommendations up front:
Invoke-Expression should generally be avoided, because it can be a security risk and introduces quoting headaches; there are usually better and safer solutions available; best to form a habit of avoiding Invoke-Expression, unless there is no other solution.
There is never a reason to use Invoke-Expression to simply execute an external program with arguments, such as ping 127.0.0.1; just invoke it directly - support for such direct invocations is a core feature of any shell, and PowerShell is no exception.
If you do need to store a command in a variable or pass it as an argument for later invocation, use script blocks ({ ... }); e.g., instead of $command = 'ping 127.0.0.1', use $command = { ping 127.0.0.1 }, and invoke that script block on demand with either &, the call operator, or ., the dot-sourcing operator.
When calling external programs, the two operators exhibit the same behavior; when calling PowerShell-native commands, & executes the code in a child scope, whereas . (typically) executes in the caller's current scope.
That Invoke-Expression $command 2>&1 doesn't work as expected looks like a bug (as of PowerShell Core 7.0.0-preview.3) and has been reported in this GitHub issue.
As for a workaround for your problem:
PetSerAl, as countless times before, has provided a solution in a comment on the question:
& { Invoke-Expression $command } 2>&1 | Tee-Object -Variable out_content
{ ... } is a script-block literal that contains the Invoke-Expression call, and it is invoked with &, the call operator, which enables applying stream-redirection expression 2>&1 to the & call, which bypasses the bug.
If $command contained a PowerShell-native command that you wanted to execute directly in the current scope, such as a function definition, you'd use . instead of &.

How to ignore specific error in PowerShell when executing a command?

I am aware ErrorAction argument, also $ErrorActionPreference,$Error and $.
Context
The issue I would like to solve is when running an external command (eg choco or git) it gives error which should be warning or not even warning, at least in my task context.
Because of their exit code PowerShell considers that result as error in any sense, for example writes out red to output, etc, which is not desirable in my task's context.
I can suppress those commands error output with -ErrorAction or 2> $null, but I have a bad feeling about completely vanishing any errors this way of the particular command.
I would like only ignore that known "not a problem in this context for me" type error.
Question
Is there any way to handle a command's error ignore some specific, but treat normally all other error conditions?
In a regular console window, in PowerShell v3 and above, stderr lines print just like stdout lines.
This is desirable, because stderr is used by many programs not just to report genuine errors, but anything that is not data, such as status messages.
Stderr lines (unless redirected - see below) print straight through the console (whereas stdout lines are sent to PowerShell's success output stream, where they can be collected in a variable, sent through the pipeline, or redirected with > / >>).
Regrettably, the PowerShell ISE, even in v5.1, does print stderr lines in red, in the same format as PowerShell errors.
Visual Studio Code with the PowerShell extension doesn't have this problem, and is worth migrating to in general, given that all future development effort will focus there, and given that it also works with the cross-platform PowerShell Core edition.
Well-behaved console applications solely use their exit code to signal success (exit code 0) vs. failure (any nonzero exit code). PowerShell saves the exit code of the most recently invoked console application in its automatic $LASTEXITCODE variable.
As an aside:
Common parameters -ErrorAction and -ErrorVariable cannot be used with external programs.
Similarly, preference variable $ErrorActionPreference has no effect (except accidentally, due to this bug, as of PowerShell v5.1 / PowerShell Core 6.2.0-preview.4).
try / catch cannot be used to detect and handle an external program's failure.
For a comprehensive overview of PowerShell's complex error handling rules, see this GitHub docs issue.
Note: I'm using the following external commands in the examples below, which produce 1 line of stdout and 1 line of stderr output (note that the redirection >&2 is handled by cmd, not PowerShell, because it is inside the '...'; it is used to produce stderr output):
cmd /c 'echo stdout & echo stderr >&2'
A variant that makes the command signal failure, via a nonzero exit code (exit 1):
cmd /c 'echo stdout & echo stderr >&2 & exit 1'
Therefore, normally the following should suffice:
$stdOut = cmd /c 'echo stdout & echo stderr >&2' # std*err* will print to console
if ($LASTEXITCODE -ne 0) { Throw "cmd failed." } # handle error
This captures stdout output in variable $stdout and passes stderr output through to the console.
If you want to collect stderr output for later and only show them in case of error:
$stdErr = #() # initialize array for collecting stderr lines.
# Capture stdout output while collecting stderr output in $stdErr.
$stdOut = cmd /c 'echo stdout & echo stderr >&2 & exit 1' 2>&1 | Where-Object {
$fromStdErr = $_ -is [System.Management.Automation.ErrorRecord]
if ($fromStdErr) { $stdErr += $_.ToString() }
-not $fromStdErr # only output line if it came from stdout
}
# Throw an error, with the collected stderr lines included.
if ($LASTEXITCODE -ne 0) {
Throw "cmd failed with the following message(s): $stdErr"
}
Note the 2>&1 redirection, which instructs PowerShell to send stderr lines (stream 2, the error stream) through the pipeline (stream 1, the success stream) as well.
In the Where-Object block, $_ -is [System.Management.Automation.ErrorRecord] is used to identify stderr lines, because PowerShell wraps such lines in instances of that type.
Alternatively, you could collect stderr output in a temporary file (2>/path/to/tmpfile), read its contents, and delete it.
This GitHub issue proposes introducing the option of collecting redirected stderr output in a variable, analogous to how you can ask cmdlets to collect errors in a variable via common parameter -ErrorVariable.
There are two caveats:
Inherently, by only printing stderr lines later, the specific context relative to the stdout output may be lost.
Due to a bug as of Windows PowerShell v5.1 / PowerShell Core 6.2.0, $ErrorActionPreference = Stop mustn't be in effect, because the 2>&1 redirection then triggers a script-terminating error as soon as the first stderr line is received.
If you want to selectively act on stderr lines as they're being received:
Note:
Inherently, as you're processing the lines, you won't yet know whether the program will report failure or success in the end.
The $ErrorActionPreference = 'Stop' caveat applies here too.
The following example filters out stderr line stderr1 and prints line stderr2 to the console in red (text only, not like a PowerShell error).
$stdOut = cmd /c 'echo stdout & echo stderr1 >&2 & echo stderr2 >&2' 2>&1 |
ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) { # stderr line
$stdErrLine = $_.ToString()
switch -regex ($stdErrLine) {
'stderr1' { break } # ignore, if line contains 'stderr1'
default { Write-Host -ForegroundColor Red $stdErrLine }
}
} else { # stdout line
$_ # pass through
}
}
# Handle error.
if ($LASTEXITCODE -ne 0) { Throw "cmd failed." }
I've come across this situation with git before, and worked around it by using $LASTEXITCODE.
Not sure if it's applicable to your situation, or to choco as I've not had issues with it.
# using git in powershell console sends everything to error stream
# this causes red text when it's not an error which is annoying
# 2>&1 redirects all to stdout, then use exit code to 'direct' output
$git_output = Invoke-Expression "& [git pull etc] 2>&1"
# handle output using exitcode
if ($LASTEXITCODE -ne 0) { throw $git_output }
else { Write-Output $git_output }

How to handle errors in a way that works the same whether the script runs in "regular" powershell console or in powershell ISE?

I have this simple script:
$ErrorActionPreference = "Stop"
try
{
cmd /c mklink a .\DataSvc.sln
}
catch
{
"Failed"
}
(file DataSvc.sln exists)
When I run it in ISE powershell console it prints "Failed", when I do it from the "regular" powershell console it outputs "You do not have sufficient privilege to perform this operation.":
ISE:
Regular:
How am I supposed to write it so that it prints "Failed" in both cases?
EDIT 1
You must run it as a regular account (not elevated) with Windows 10 Developer Mode turned off. If you do not know what Windows 10 Developer Mode is, then you are fine (for this question).
Unfortunately, different hosts treat stderr output from external programs differently.
The ISE routes stderr output to PowerShells own error stream, which explains why anything written to stderr triggers the try / catch handler.
On a side node: Consider switching from the obsolescent ISE to Visual Studio Code with its PowerShell extension. Future development efforts are focused there, and the behavior doesn't differ from the console (at least in this respect).
The regular console patches stderr output through to the console, in which case no error is triggered.
Due to a bug, you can currently (Windows PowerShell v5.1 / PowerShell Core v6.1) trigger an error in the console just by redirecting stream number 2 in PowerShell:
$ErrorActionPreference = "Stop"
try {
cmd /c 'echo tostderr >&2' 2>&1 # even 2>$null would trigger an error(!)
} catch {
"Failed"
}
However, I wouldn't rely on that, as the bug may - and hopefully will - get fixed.
Taking a step back: As implied by the link in the comments, whether an external program failed should only ever derived from its exit code, not from the presence of stderr output, as many program use stderr output to report information other than errors (such as diagnostic information or mere warnings).
Thus, if ($LASTEXITCODE -ne 0) alone should be used to determine failure.
If, for some reason, you do need to infer failure from the presence of stderr output - e.g., because some programs don't properly reflect failure in their exit codes - you can try the following approach, which should work now as well as after the aforementioned bug is fixed:
$ErrorActionPreference = "Stop"
try {
cmd /c 'echo tostderr >&2' 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) { Throw $_ }
$_
}
} catch {
"Failed"
}
This relies on merging the error stream into the success stream and then detecting stderr-originated lines by their type.
Note that while PowerShell-internally you can collect a command's error output in a variable with common parameter -ErrorVariable / -ev, there is no analogous mechanism when calling external programs; however, introducing such a mechanism has been proposed in this GitHub issue.