Powershell Import-Csv New-AdUser skip if user exists - powershell

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"
}

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.

Related

How to do error handling when creating AD users

I was having issues with my IF statement to check if my users already exist within AD , I have tried the Get-AD user is eq null however my IDE says that you cannot put null there. I was hoping in my script to loop through each user in my csv file and record the terminal output to my log and create an AD user if its not in the csv file. I have been scratching my head all day on how to achieve this
Import-Module ActiveDirectory
$Log_File = "C:\PS\Logs\$env:UserName_ad_script.log"
Start-Transcript -path $Log_File -append
if (Test-Path $Log_File) {
echo "logging to $Log_File"
}
else {
New-Item $Log_File -ItemType Directory
echo "Log file created ....."
}
$ADUsers = Import-Csv C:\users.csv # or path of pyhton code
foreach ($User in $ADUsers) {
$FirstName = $User.FirstName
$LastName = $User.LastName
$username = $FirstName.$LastName
$password = $User.passcode
$Title = $User.Title
$Manager_Email = $User.Manager_Email
$AdUser_exists = Get-ADUser -Identity $username
if ($AdUser_exists -eq null) {New-ADUser -Name $Name -SamAccountName $username -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -Title $Title
Enable-AdAccount -Identity $username
Set-ADUser -Identity $username -ChangePasswordAtLogon $true
}
else {echo "user already exists"}
}
Stop-Transcript
You can also use [string]::IsNullOrWhiteSpace() function to check for null.
if ([string]::IsNullOrWhiteSpace($AdUser_exists)) {
New-ADUser -Name $Name -SamAccountName $username -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -Title $Title
Enable-AdAccount -Identity $username
Set-ADUser -Identity $username -ChangePasswordAtLogon $true
}
else {
echo "user already exists"
}

Create and Map Home Directory for AD Users using PowerShell in Bulk

I am trying to create a script to add users to my AD in bulk.
I use a .csv file for this.
So far I am able to add the users in bulk, however I am stuck on how to also create a home directory with the standard homedirectory permissions. If anyone has a solution or tips, I would appreciate that.
my script so far:
$pw = read-host "Password" -AsSecureString
Import-CSV F:\Scripts\newusers\usersVoorbeeldDannyWijnsema.csv | foreach `
{New-ADUser `
-Name $_.Name `
-SamAccountName $_.SamAccountName `
-GivenName $_.GivenName `
-Surname $_.Surname `
-DisplayName $_.DisplayName `
-UserPrincipalName $_.UserPrincipalName `
-AccountPassword $pw `
-ChangePasswordAtLogon $true `
-Enabled $true `
-Path 'OU=N43,OU=Students,DC=example,DC=local' `
-HomeDir ='\\Example-DC01\UserFolders\$($_.SamAccountName)' `
-DriveLetter ='Z:' `
}
Try this:
$pw = read-host "Password" -AsSecureString
Import-CSV F:\Scripts\newusers\usersVoorbeeldDannyWijnsema.csv | foreach {
New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Surname $_.Surname -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -AccountPassword $pw -ChangePasswordAtLogon $true -Enabled $true -Path 'OU=N43,OU=Students,DC=example,DC=local'
$homeShare = "Home share path"
$DriveLetter = "Z:"
$user = Get-ADUser $_.sAmAccountName
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
 $AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ErrorAction Stop
}
Attribution: https://activedirectoryfaq.com/2017/09/powershell-create-home-directory-grant-permissions/
I modified script found there.
This script creates an ACL object and Grants standard homedirectory permission to each created AD user from CSV.

can't create userS via powershell

I can't import users in powershell with a script via an csv file, but If I print the parameters on the screen,it shows them as it should.
what I am doing wrong? in my life plenty with that mustache, but plis focus on the script.
is running windows server 2016 on the powershell ise, on virtualbox
The Script:
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "991-5D"}))
{New-ADOrganizationalUnit "991-5D" -Path (Get-ADDomain).DistinguishedName}
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "911-5V"}))
{New-ADOrganizationalUnit "911-5V" -Path (Get-ADDomain).DistinguishedName}
$domain=(Get-ADDomain).DNSRoot
Import-Csv -Path "C:\Alumnos.csv" | foreach-object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
//there are many others O.U.
$ou= "UO="+$UO+","+$domain
$UPN = $_.LETRA+$_.PATERNO+$_.X+"#"+ "$domain"
$CUENTA= $_.LETRA+$_.PATERNO+$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $_.NOMBRE
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN -AccountPassword
(ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou
-Enabled $true -ChangePasswordAtLogon $true -Verbose}
the data:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
10,ARÉVALO,CORNEJO,NICOLÁS,ALEJANDRO,N
11,BARRIOS,MONTERO,BENJAMÍN,IGNACIO,B
12,BUSTAMANTE,LOYOLA,IGNACIO,HERNANDO,I
13,BUSTOS,GARRIDO,ARTURO,IGNACIO,A
this are the results on each line:
+ New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:NotSpecified: (CN=IGNACIO,UO=9...da.com:String)
[New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,
Microsoft.ActiveDirectory.Management.Commands.NewADUser
the head:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
echo:
#{X=42; PATERNO=PAYACÁN; MATERNO=ZAPATA; NOMBRE=NICOLÁS; SEGUNDO=N; LETRA=}.NOMBRE
I know that reads the file and instead of reading just the column reads all the line($_), and then prints whatever I wrote next to it(".name", ".section", etc).
I've made some variable and format changes to make this code more successful.
$domain=Get-ADDomain
Import-Csv -Path "C:\Alumnos.csv" |
Foreach-Object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
$ou = "OU={0},{1}" -f $UO,$domain.DistinguishedName
$UPN = "{0}{1}{2}#{3}" -f $_.LETRA,$_.PATERNO,$_.X,$domain.DNSRoot
$CUENTA= "{0}{1}{2}" -f $_.LETRA,$_.PATERNO,$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $UPN -Name $_.NOMBRE `
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN `
-AccountPassword (ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou `
-Enabled $true -ChangePasswordAtLogon $true -Verbose
}
Explanation:
$domain: I've made this an ADDomain object. This allows the DistinguishedName and DNSRoot properties to be accessed where appropriate.
-f operator: I used the format operator to make it easier to read the string concatenation attempts.
$ou: This is constructed using the DistinguishedName of the domain. This is the proper format for the OU path.
$UPN: This is constructed using the DNSRoot of the domain. It can obviously be different than your domain, but must be in an email address or FQDN format.
Additional Comments:
You are setting -Name to be $_.NOMBRE. This could be problematic because Name must be unique in each OU. Name is used to build the CN, which is where uniqueness is required. If you have NICOLAS in OU 991-5D, you are going to get an error if you try to create another NICOLAS in the same place. IMHO, I would do something different. You could also implement the use of splatting for building the properties of your New-ADUser command, but that is only for readability purposes. Below is an example of splatting:
$NewUserProperties = #{
SamAccountName = $CUENTA
UserPrincipalName = $UPN
Name = $_.NOMBRE
Surname = $_.PATERNO
GivenName = $_.NOMBRE
EmailAddress = $UPN
AccountPassword = (ConvertTo-SecureString "Leica666" -AsPlainText -force)
Path = $ou
Enabled = $true
ChangePasswordAtLogon = $true
}
New-ADUser #NewUserProperties -Verbose

Adding newly created users to pre-existing groups

This script currently creates new users after importing data from a CSV file
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
}
This is the csv file I am importing from:
Name,samAccountName,ParentOU,Group
Test Test1,TTest1,"OU=Business,DC=NWTC,DC=local",TestGroup
After a user is created, I want to add them to an already exisiting group. There will be different groups I want different users to be added to, but only 1 group per person.
I've been playing around with Add-AdGroupMember, but I'm not sure how to proceed. Something like this: Add-ADGroupMember -Members $_.Members. This is the first time I'm working with CSVs, so I'm in new territory
New-ADuser does not support this functionality so you will have to do that yourself after the fact. What you could do is have New-ADUser spit out the AD user object it creates and use that with Add-ADGroupMember.
$newUserProperties = #{
Name = $_.Name
Path = $_."ParentOU"
SamAccountName = $_."samAccountName"
UserPrincipalName = $_."samAccountName" + "#NWTC.local"
AccountPassword = (ConvertTo-SecureString "Password1" -AsPlainText -Force)
ChangePasswordAtLogon = $false
Enabled = $true
}
try{
$newADUser = New-ADUser #newUserProperties -PassThru
Add-ADGroupMember -Identity $_.Group -Members $newADUser.SamAccountName
} catch {
Write-Warning "Could not create $($newUserProperties.samaccountname)"
}
The error handling is crude but should exist in some form to account for failures in the source data or misconceptions of existing users. Basically just getting $newADUser and using it for Add-ADGroupMember
We use splatting of the parameters here. That way you don't have to worry about having nice formatted code by using backticks.
Add the Add-ADGroupMember in the ForEach-Object after the new user is created :
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
Add-ADGroupMember -Identity 'AD_GROUP_WHERE_YOU_ADD_MEMBERS' -Members $_.samAccountName
}

Bulkuser creation in AD using powershell

I am trying to upload bulk users to my AD using the code below.
But it keep giving me an error.
import-csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath Set-ADAccountPassword -Identity $_.SamAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) Enable-ADAccount -Identity $_.SamAccountName }
The error is as attached.
You need a statement terminator for the New-ADUser cmdlet, before calling Set-ADAccountPassword.
You can either use ;, or place Set-ADAccountPassword on a separate line:
Import-Csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {
New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath
Set-ADAccountPassword -Identity $_.SamAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force)
Enable-ADAccount -Identity $_.SamAccountName
}
You can also chain the commands together in a single pipeline, if you use the -PassThru switch on New-ADUser and Set-ADAccountPassword (notice the | at the end of each line):
Import-Csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {
New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath -PassThru |
Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) -PassThru |
Enable-ADAccount
}