Link to home
Start Free TrialLog in
Avatar of Radim88
Radim88

asked on

Powershell error handling

Hello,

Pls would you advice, I have service account, and in description is written samaccount name of the user. I am extracting it with regex. But how can I do it, that when user is not there it will write-output me that user is not there. I am trying it with try/catch or trap but no output. Please advice.

Many thanks




Get-QADUser -Enabled 'xxxx' -LdapFilter "((!sAMAccountName=Vxx*)(!sAMAccountName=xxx*))" |
%{ 

try{
$descSamAccount = $_ |%{[regex]::Match($_.description,"\w\d{7}")}
$descNameMail = $descSamAccount.value | Get-QADUser `
-ErrorAction Stop | select -ExpandProperty email 
$descNameMail

}
catch
{
Write-Output "user is not set or doesnt exists"
}

Open in new window

Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey :)

Perhaps like this.
Get-QADUser -Enabled 'xxxx' -LdapFilter "((!sAMAccountName=Vxx*)(!sAMAccountName=xxx*))" | ForEach-Object {
  If ($_.Description -Match '\w\d{7}') {
    $User = Get-QADUser -SamAccountName $Matches[0]
    If ($User) {
      $User | Select-Object -ExpandProperty Email
    } Else {
      Write-Host "Could not find user"
    }
  } Else {
    Write-Host "Username not set"
  }
}

Open in new window

Chris
To answer your question, I do not suspect an error will occur when a lookup fails because no error is generated.  It simply does not return a result, therefore the the catch block has nothing passed to it and the control falls through.  Chris' script shifts from a try catch-block to the if-then pattern.  This focuses on a boolean result instead an error result, which, in this case is what you would expect.
Avatar of Radim88
Radim88

ASKER

thanks a lot, I was only curious about this:  -ErrorAction Stop  , it wont set it as a stop error?

Thx
ASKER CERTIFIED SOLUTION
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Radim88

ASKER

thx a lot