Redirect standard error to a variable in PowerShell
I would like to script a dcdiag test to alert me if it finds any errors. I thought I may able to do this in PowerShell by...
$test = dcdiag 2>$err
I don't have any errors from dcdiag at the moment, so I couldn't test that directly, but I wrote another PowerShell script to throw an exception, hoping I could test this method using that script. This didn't work using the method above so I opted for:
try {
$test = dcdiag
}
catch {
$err = $_.Exception.Message
}
It worked for my test case, but I don't know if this will pick up standard error from dcdiag.
How should I best achieve standard error redirect to a variable in PowerShell given I would like to use it with dcdiag?
Solution 1:
try...catch
wouldn't help in this case.
You might want to do:
$test = dcdiag 2>&1
$err = $test | ?{$_.gettype().Name -eq "ErrorRecord"}
if($err){
# Error has occurred
}