Hello team,

I’m looking for a PShell script that checks if user exists before it creates new one. If it finds user exists I want it to show it in a different color with which OU the account exists and then continue to create the rest of the users from CSV. I’ve tried saveral scripts but none worked for me. I also tried Try and catch option still no luck.

Thanks

2 Spice ups

Can you please share what you have tried so far? We are happy to help but don’t write scripts for you

If you post code, please use the ‘Insert Code’ button. Please and thank you!

codebutton2.png

Write-Host 'Start Process'
Write-Host '-------------------------------------'

    # Read the CSV file

    Write-Host 'Reading the CSV file......'
    
    #Loop through all items in the CSV file

    Import-Csv "E:\BulkADUsers-CSV1.csv" | ForEach-Object {

$userPrincinpal = $_."samAccountName" + "@mycomp.local"
 $Drive = "U"

$userPrincinpal = Get-ADuser -LDAPfilter "(samaccountname=$userPrincinpal)"}

if ($userPrincinpal -eq $null) {

try {

New-ADUser -Name $_.Name `
 -Path $_."OU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "P@ssword1" -AsPlainText -Force) `
 -ChangePasswordAtLogon $false -Enabled $true -EmailAddress ($_."samAccountName" + "@mycomp.com") -Surname $_.Surname -GivenName $_.GivenName -DisplayName $($_."Surname" + "," + " " + $_."GivenName") `
 -homedirectory "\\SERVER\Users\$($_.sAMAccountName)" -HomeDrive $Drive -Description $_.Info -EmployeeID $_.EID `
 -OtherAttributes @{extensionAttribute1=($_.EID); proxyAddresses=("SMTP:"+$_.sAMAccountName+"@mycomp.com")} -Department $_.Dept -PassThru
Add-ADGroupMember "All Employees" $_."samAccountName";
Add-ADGroupMember "AllSharePointUsers" $_."samAccountName";
}

catch {
    Write-Host 'Error:'  $($_.CategoryInfo) -ForegroundColor Yello
    Write-Host 'Message:' $($_.Exception.Message) -ForegroundColor magenta

    Write-Host '-----------------------------------------------------------------'
    Write-Host 'End Process'
    }}

The result of above message is…

@alexw

Holy… other than that being quite a large script to create a new user, it looks like it is not closing the bracket for the foreach look and thus does not get the pipe value ($_.name)

Import-Csv "E:\BulkADUsers-CSV1.csv" | 
ForEach-Object {
    $userPrincinpal = $_."samAccountName" + "@mycomp.local"
    $Drive = "U"
    $userPrincinpal = Get-ADuser -filter {samaccountname -eq $userPrincinpal}
    
    if ($userPrincinpal -eq $null) {
        try {
            New-ADUser -Name $_.Name `
            -Path $_."OU" `
            -SamAccountName  $_."samAccountName" `
            -UserPrincipalName  $userPrincinpal `
            -AccountPassword (ConvertTo-SecureString "P@ssword1" -AsPlainText -Force) `
            -ChangePasswordAtLogon $false -Enabled $true -EmailAddress ($_."samAccountName" + "@mycomp.com") -Surname $_.Surname -GivenName $_.GivenName -DisplayName $($_."Surname" + "," + " " + $_."GivenName") `
            -homedirectory "\\SERVER\Users\$($_.sAMAccountName)" -HomeDrive $Drive -Description $_.Info -EmployeeID $_.EID `
            -OtherAttributes @{extensionAttribute1=($_.EID); proxyAddresses=("SMTP:"+$_.sAMAccountName+"@mycomp.com")} -Department $_.Dept -PassThru -WhatIf
            Add-ADGroupMember "All Employees" $_."samAccountName";
            Add-ADGroupMember "AllSharePointUsers" $_."samAccountName";
        }catch{
            Write-Host 'Error:'  $($_.CategoryInfo) -ForegroundColor Yello
            Write-Host 'Message:' $($_.Exception.Message) -ForegroundColor magenta
        }
    }
}

I did not really try it at all though, but that’s what it looks like from the error message you shared.

ForEach-Object { 
    $userPrincinpal = $_."samAccountName" + "@mycomp.local" 
    $Drive = "U" 
    $userPrincinpal = Get-ADuser -filter {samaccountname -eq $userPrincinpal**}** <------- no, the brace is here. 

So that needs to be deleted. Also, the Get-ADUser check may throw and error if the user does not exist. So that is an error you’ll need to handle too. (editor seems borked tonight).

Also, you;ll need to change the check for an existing user:

    $userExists = Get-ADuser -filter {samaccountname -eq $userPrincinpal}
    
    if ($userExists -eq $null) {

previously $userPrincinpal was $null when you were creating the user.

Neally! Your script did work. Thank you. I want to know just for curiosity…Having so many OUs when it detects existing user account it does not show entire OU path for user. What code should I use if I want to know which samaccount already exist including full path of OU. I want to add this info in “Message”: line.

Thank you again for your help…

Neally! Your script did work. Thank you. I want to know just for curiosity…Having so many OUs when it detects existing user account it does not show entire OU path for user. What code should I use if I want to know which samaccount already exist including full path of OU. I want to add this info in “Message”: line.

Hmm, if you are getting this message then the Get-ADUser check has actually failed to work properly.

Its not actually, because I left Tets2 user intentionally to see if this script detects and it did. So instead of getting that long string in Yellow I rather want to have samaccount name and which OU the existing user is in.

Thanks…

Assuming I understand you…

Import-Csv "E:\BulkADUsers-CSV1.csv" | 
ForEach-Object {
    $userPrincinpal = $_."samAccountName" + "@mycomp.local"
    $Drive = "U"
    $userExists = Get-ADuser -filter {samaccountname -eq $userPrincinpal}
    
    if ($userExists -eq $null) {
        # <snip>
    } else {
        Write-Host $userExists.DistinguishedName
    }

}

some code was deleted for clarity. Note that I’m using $userExists for the user check.

The else block should give you what you want. Though I might be mistaken on the exact parameter name.

Import-Csv "G:\BulkADUsers-CSV1.csv" | 
ForEach-Object {
    $userPrincinpal = $_."samAccountName" + "@mycomp.local"
    $Drive = "U"
    $userPrincinpal = Get-ADuser -filter {samaccountname -eq $userPrincinpal}
    
    if ($userPrincinpal -eq $null) {
        try {
            New-ADUser -Name $_.Name `
            -Path $_."OU" `
            -SamAccountName  $_."samAccountName" `
            -UserPrincipalName  $userPrincinpal `
            -AccountPassword (ConvertTo-SecureString "P@ssword1" -AsPlainText -Force) `
            -ChangePasswordAtLogon $false -Enabled $true -EmailAddress ($_."samAccountName" + "@mycomp.com") -Surname $_.Surname -GivenName $_.GivenName -DisplayName $($_."Surname" + "," + " " + $_."GivenName") `
            -homedirectory "\\SERVER\Users\$($_.sAMAccountName)" -HomeDrive $Drive -Description $_.Info -EmployeeID $_.EID `
            -OtherAttributes @{extensionAttribute1=($_.EID); proxyAddresses=("SMTP:"+$_.sAMAccountName+"@mycomp.com")} -Department $_.Dept -PassThru
            Add-ADGroupMember "All Employees" $_."samAccountName";
            Add-ADGroupMember "AllSharePointUsers" $_."samAccountName";
        }catch{
            Write-Host 'Error:'  $($_.CategoryInfo) -ForegroundColor Yello
            Write-Host 'Message:' $($_.Exception.Message) -ForegroundColor magenta
             
        }
    }
}
Name samAccountName OU GivenName Surname Dept EID Info

The code is working just OK and I really appreciate everyone helping me on this. However, I noticed one thing that, it does not populate “User logon name” box in AD. Above line is header of my CSV file. I’m not sure what causes not to populate the field. I’ve to type UPN manually and from drop down arrow and choose domain name.

Thank you in advance. Have a great weekend!

My replies tell you why this happens. It is the reason I created a new variable to hold the output of the Get-ADUser command.

This command overwrite the contents of $userPrincinpal

$userPrincinpal = Get-ADuser -filter {samaccountname -eq $userPrincinpal}