user3594093
user3594093

Reputation: 15

Powershell Import-Csv New-AdUser skip if user exists

I have a fully functional script to import and create AD Users, but I would like to skip from attempting to create Users that are already in AD.

Import-Module ActiveDirectory

$CsvPath = "C:\Shares\Users.csv"
$CsvTest = Test-Path $CsvPath

Import-Csv $CsvPath | ForEach-Object {
Get-AdUser $_.sAMAccountName
}

Import-Csv $CsvPath | ForEach-Object {  
New-ADUser -Name $_.Name -UserPrincipalName $_.userPrincipalName -SamAccountName $_.sAMAccountName -DisplayName $_.DisplayName -GivenName $_.GivenName -Surname $_.Surname -AccountPassword (ConvertTo-SecureString $_.Password  -AsPlainText -force)  -Enabled $true -ChangePasswordAtLogon $true

{

Catch [Microsoft.ActiveDirectory.Management.Commands.NewADUser] 

}
    $_."sAMAccountName";  "already exists"
    }

Upvotes: 0

Views: 6365

Answers (1)

Ashigore
Ashigore

Reputation: 4678

Something like this without relying on exceptions would be better:

Import-Module ActiveDirectory

$csvPath = "C:\Shares\Users.csv"

if (Test-Path $csvPath)
{
    $newUsers = Import-Csv $csvPath
    $existingUsers = Get-ADGroupMember "Domain Users"

    foreach ($newUser in $newUsers)
    {
        if (($existingUsers | Where-Object { $_.sAMAccountName -eq $newUser.sAMAccountName }) -eq $null)
        {
            $user = New-ADUser -Name $newUser.Name -UserPrincipalName $newUser.userPrincipalName -SamAccountName $newUser.sAMAccountName -DisplayName $newUser.DisplayName -GivenName $newUser.GivenName -Surname $newUser.Surname -AccountPassword (ConvertTo-SecureString $newUser.Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true
        }
    }
}

Personally I prefer to use the Quest AD Module for Powershell as it avoids exceptions by returning $null when an object doesn't exist.

Upvotes: 1

Related Questions