20

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?

1 Answer 1

21

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
}
6
  • 3
    Ah, I didn't say in the original question; is it possible to keep both stdout and stderr? i.e $test = stdout and $err = stderr?
    – Matt
    Dec 14, 2011 at 2:14
  • 2
    @Ablue - $test will have both, that is why I am filtering out the error to $err.
    – manojlds
    Dec 14, 2011 at 2:15
  • 1
    Make sure $ErrorActionPreference is not set to "SilentlyContinue". When it is the errors stream is not available.
    – cmcginty
    Oct 28, 2015 at 21:33
  • @cmcginty actually $ErrorActionPreference should be set to "Continue". Using SilentlyContinue will only capture stdout as stderr will be completely removed (at least on powershell 5) Mar 23, 2017 at 18:02
  • 2
    @Simon Correct, I said DO NOT use SilentlyContinue.
    – cmcginty
    Mar 24, 2017 at 19:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .