Reputation: 181
This must be a very simple solution, but I can't for the life of me figure out how to redirect errors/warnings to standard output.
Right now, I'm capturing the output of stuff by assigning it to a variable, without worrying about formatting etc, so for example:
$buffer += Whatever-Cmdlet
But what I would like to do is also capture any error message into that variable. Like doing 2>&1.
Is there any way to make this work? I did try:
$buffer += Whatever-Cmdlet 2>&1
without success.
Thanks for any assistance!
Upvotes: 2
Views: 4251
Reputation: 200503
It depends on which version of PowerShell you're running. In PowerShell v2 warnings are written to the host and thus cannot be captured in a variable. In PowerShell v3 warnings are written to a separate output stream, so you have to redirect the warning stream as well as the error stream to capture errors and warnings:
$buffer += Whatever-Cmdlet 2>&1 3>&1 | Out-String
See Get-Help about_Redirection
for more information.
Upvotes: 0
Reputation: 68341
Not tested thoroughly, but
$buffer += Whatever-Cmdlet -WarningVariable +buffer -ErrorVariable +buffer
if you have v3/4:
$PSDefaultParameterValues=@{"*:WarningVariable"="+buffer";"*:ErrorVariable"="+buffer";}
Should do it for all the cmdlets your run after you set that.
Upvotes: 2
Reputation: 181
Actually, it turns out as long as you pipe the output:
$buffer += Whatever-Cmdlet 2>&1 | Out-String
It seems to work. Thanks!
Upvotes: 1