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?

Peter Mortensen
  • 2,319
  • 5
  • 23
  • 24
Ablue
  • 1,140
  • 1
  • 12
  • 32

1 Answers1

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
}
Peter Mortensen
  • 2,319
  • 5
  • 23
  • 24
manojlds
  • 346
  • 2
  • 5
  • 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? – Ablue Dec 14 '11 at 02:14
  • 2
    @Ablue - `$test` will have both, that is why I am filtering out the error to `$err`. – manojlds Dec 14 '11 at 02:15
  • 1
    Make sure $ErrorActionPreference is not set to "SilentlyContinue". When it is the errors stream is not available. – cmcginty Oct 28 '15 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) – Simon Bergot Mar 23 '17 at 18:02
  • 2
    @Simon Correct, I said DO NOT use SilentlyContinue. – cmcginty Mar 24 '17 at 19:37
  • Reverse the filter to get stdout without the error (but still capture stderr) `$test | ?{$_.gettype().Name -ne "ErrorRecord"}` – Shawn McGough Feb 08 '20 at 01:44