srbob
srbob

Reputation: 563

Error handling in PowerShell provoked by a null dsquery

I want to avoid errors provoked by a null dsquery. I tried this:

try {
     dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch [Exception] {
    return $_.Exception.Message
}

But I'm still getting:

dsget : dsget failed:'Target object for this command' is missing.
At ExpiringCertificates.ps1:35 char:49
+         dsquery user forestroot -samid $a[$i] | dsget user -email | Select-Strin ...
+                                                 ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (dsget failed:'T...nd' is missing.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

type dsget /? for help.

How should I handle it?

Upvotes: 2

Views: 1373

Answers (3)

Mark Bertenshaw
Mark Bertenshaw

Reputation: 5689

dsquery and dsget are not PowerShell commands, so PowerShell looks at the standard error, and processes it, turning it into an ErrorRecord with a "NativeCommandError" exception attached to it, and then sends a text representation of that record to the standard output.

However, if you process the standard error yourself, you have a bit more flexibility:

dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line 2>&1
If ($_ -is [Management.Automation.ErrorRecord]) {
    $message = $_.Exception.Message
    # Do what you want with $message.
} Else {
    $_ >> output.txt
}

Upvotes: 1

skataben
skataben

Reputation: 2152

Try this:

try
{
    dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch
{
    Write-Error -ErrorRecord $_
}

If $ErrorActionPreference is set to 'Stop', Write-Error will throw an exception and halt execution. Otherwise, it will print to the error stream and continue execution. This allows the caller to decide whether or not to continue on error and keeps you from having to set global variables in your scripts.

If you need to print and return the error message, use the -ErrorVariable parameter:

catch
{
    $errorVar = $null
    Write-Error -ErrorRecord $_ -ErrorVariable errorVar
    return $errorVar
}

Or, if you need to return the error message without printing it, add the "2>" redirect:

catch
{
    $errorVar = $null
    Write-Error -ErrorRecord $_ -ErrorVariable errorVar 2> $null
    return $errorVar
}

Upvotes: 1

saw
saw

Reputation: 34

This might work for you:

try {
     $erroractionpreference = 'stop'
     dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >output
}
catch [Exception] {
    return $_.Exception.Message
}

Upvotes: 0

Related Questions