how to use try catch to handle error on new-azureaduser commandlet

Saeed Ahmad 21 Reputation points
2022-11-22T06:35:48.91+00:00

Hi I am having difficulty how to catch errors from New-AzureADUser command and get meaning full errors messages with variable.
I am using below script to loop through csv file and run new-azureaduer. It runs fine but I like to capture error message and the user name for which error generated.
This is my script
$users = $null

$users = <a CSV file with user list to be created>

foreach ($user in $users){
try {
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = $user.Password
$PasswordProfile.ForceChangePasswordNextLogin = $false
$SignInName = New-Object -TypeName Microsoft.Open.AzureAD.Model.SignInName
$SignInName.Type = "emailAddress"
$SignInName.Value = $user.email

New-AzureADUser -DisplayName $user.DisplayName `  
              -AccountEnabled $true `  
              -SignInNames $SignInName `  
              -MailNickName $($User.DisplayName).replace(" ","-") `  
              -Mobile $User.Mobile `  
              -GivenName $user.DisplayName `  
              -PasswordProfile $PasswordProfile `  
              -CreationType LocalAccount `  
              -JobTitle "Customer" `  
              -CompanyName "Basix-Batch1" `  
              -PostalCode $user.PostalCode  

}

Catch  
{  

Write-Warning $Error[0].exception.Message
}
}

++++++++++++++++++++++++++++++++++++
I get below in output. I wonder if I can get help to export the errors to csv file with "Message" and UserName

WARNING: Error occurred while executing NewUser
Code: Request_BadRequest
Message: Another object with the same value for property userPrincipalName already exists.
RequestId: 1ddde54f-a05d-41ca-8b33-a31a9cd81d98
DateTimeStamp: Tue, 22 Nov 2022 06:31:34 GMT
Details: PropertyName - userPrincipalName, PropertyErrorCode - ObjectConflict
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed

Thank you

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,448 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Mhd Samer Sawas 151 Reputation points
    2022-11-23T05:11:07.877+00:00

    @Saeed Ahmad

    The modified script below will send error messages and display names to a log file in addition to showing them on screen:

    $LogFile = "$PSScriptRoot\Log.csv"  
    Clear-Content -Path $LogFile -Confirm -ErrorAction SilentlyContinue  
    $users = $null  
    #$users = <a CSV file with user list to be created>  
    foreach ($user in $users){  
        try {  
            $PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile  
            $PasswordProfile.Password = $user.Password  
            $PasswordProfile.ForceChangePasswordNextLogin = $false  
            $SignInName = New-Object -TypeName Microsoft.Open.AzureAD.Model.SignInName  
            $SignInName.Type = "emailAddress"  
            $SignInName.Value = $user.email  
            New-AzureADUser -DisplayName $user.DisplayName `  
                            -AccountEnabled $true `  
                            -SignInNames $SignInName `  
                            -MailNickName $($User.DisplayName).replace(" ","-") `  
                            -Mobile $User.Mobile `  
                            -GivenName $user.DisplayName `  
                            -PasswordProfile $PasswordProfile `  
                            -CreationType LocalAccount `  
                            -JobTitle "Customer" `  
                            -CompanyName "Basix-Batch1" `  
                            -PostalCode $user.PostalCode `  
                            -ErrorAction Stop  
        }  
        Catch {  
            [PSCustomObject]@{  
                'UserName' = $user.DisplayName  
                'Message'  = $Error[0].exception.Message  
                } | Export-Csv $LogFile -Append -NoTypeInformation  
            $ErrorMessage = $Error[0].exception.Message  
            Write-Warning "Error creating user $($user.DisplayName). $ErrorMessage"   
        }  
    }  
    

    Please don't forget to upvote and "Accept as answer" if I answered your question.

    0 comments No comments