noelmm Posted March 31, 2017 Posted March 31, 2017 (edited) Hi everyone, I'm new to powershell and have attempted to write a script to bulk import users into AD, I have read around a few sites but I'm having trouble with the whole process. I have my test server AD setup as follows domain = test.com OU-School name OU - Site Users OU - Staff OU - Admin OU - Teacher OU - Archive OU - Student OU - Year 7 OU - Year 8 OU - Year 9 OU - Year 10 OU - Year 11 OU - Archive OU- Technical I have the following script and csv that will import users however the users are always imported into the generic users OU within AD, not the OU I am defining within the CSV and the account user details are not populated fully. When the users are imported the account is created the only user information that is completed is the Pre-Windows 200 logon section, the user must change password on next login is ticked (as I would expect as this is set to true) however the account is disabled although I have enabled set to true. Import-Module ActiveDirectory Import-Csv "C:\Users\Administrator\NewUsers.csv" | ForEach-Object { # $userPrincinpal = $_."samAccountName" + "@test.com" New-ADUser -Name $_.Displayname ` #-SamAccountName $_.samAccountName -UserLogonName $samAccountName -UserPrincipalName $userPrincinpal -AccountPassword (ConvertTo-SecureString "Password2017" -AsPlainText -Force) ` -ChangePasswordAtLogon $true ` -Enabled $true -Path $_."ParentOU" ` } CSV Structure Firstname,Surname,name,Display name,SamAccount,Description,Office,email,Enabled Password,Path test,student1,test.student1,test.student1,test.student1,Student Account,school name,[email protected],$True,Password2017,OU=schoolname,OU=Users,OU=Student,OU=Year 7,DC=test,DC=com A couple of questions. How can I populate the fields of the user account that I would like to? Is there anyway to force the users into the exact OU that I want to use? Thanks for any help you can offer. As I have said I am new to Powershell so please keep it simple. Noel Edited March 31, 2017 by noelmm
pcstru Posted March 31, 2017 Posted March 31, 2017 You need to create the account and then move it to the target OU. Some sample code here.
noelmm Posted March 31, 2017 Author Posted March 31, 2017 HI pcstru, I've taken a quick look and the script is beyond m knowledge at the moment so I will need to learn hat it all means. I would like to use he csv for more of the variables rather than hard coding it into the script. Noel
glen_j Posted March 31, 2017 Posted March 31, 2017 take a look at this, should help a bit https://social.technet.microsoft.com/wiki/contents/articles/24541.powershell-bulk-create-ad-users-from-csv-file.aspx
noelmm Posted March 31, 2017 Author Posted March 31, 2017 Hi everyone, Thanks for your replies and advice with this. I have now adapted the script from the link above posted by glen_j so it looks like this import-module activedirectory $users = Import-Csv "C:\Users\Administrator\Userlist.csv" ForEach ($User in $Users) { $Displayname = $User.Firstname + "." + $User.Lastname $UserFirstname = $User.Firstname $Lastname = $User.Lastname $OU = $User.OU $SAM = $User.SAM $UPN = $User.Firstname + "." + $User.Lastname + "@test.com" $Description = $User.Description $Password = $User.Password New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName "$SAM" -UserPrincipalName "$UPN" -GivenName "$UserFirstname" -Surname "$Lastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $true -PasswordNeverExpires $false -Server test.com } with the source csv file looking like this Firstname,Lastname,Maildomain,SAM,OU,Password,Description Test1,User1,test.com,Test1.User1,OU=school,OU=Users,OU=Student,OU=Year 7,DC=domain,DC=loc,Password2017,Student Account The problem is now when I run the script I receive the following error message and no user accounts are created CategoryInfo : ObjectNotFound: (CN=Test1.User1,...DC=test,DC=com :String) [New-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.NewADUser Any idea what is causing this error, I’m guessing something simple that I have overlooked. Noel
noelmm Posted March 31, 2017 Author Posted March 31, 2017 Ok I've just taken out the -Path "$OU" par of the script and it works. The script for some reason is attempting to place the user in a container called test1.user1 and I don't know, as far as I can tell I am not telling it to.
gh5000 Posted March 31, 2017 Posted March 31, 2017 Just to check but does your csv not give an error since the OU (OU=User s,OU=Student,OU=Year 7,DC=domain,DC=loc) has extra commas Also why does your error say (CN=Test1.User1,...DC=test,DC=com :String) - DC=test,DC=com. Where is test.com come from? Have you left an old variable in there somewhere. Your powershell script is hard to read as it is written above. Put each command on a separate line. As for the CSV import you could set the OU column to be just 7. Then in your powershell script have if($User.OU -eq "7") { $OU = "OU=school,OU=User s,OU=Student,OU=Year 7,DC=domain,DC=loc" } Repeat that for each possible iteration - 8, 9, 10, Staff, Tech, Admin etc
noelmm Posted April 3, 2017 Author Posted April 3, 2017 Hi everyone, I have now got the script working so that the user accounts are created within the generic users OU with AD (code for script is below). import-module activedirectory$users = Import-Csv .\Userlist-sn.csvForEach ($User in $Users){ $Displayname = $User.Firstname + "." + $User.Lastname $UserFirstname = $User.Firstname $Lastname = $User.Lastname $OU = $User.OU $SAM = $User.SAM $UPN = $User.Firstname + "." + $User.Lastname + "@test.com" $Description = $User.Description $Password = $User.Password New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName "$SAM" -UserPrincipalName "$UPN" -GivenName "$UserFirstname" -Surname "$Lastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -PasswordNeverExpires $false -Server test.com #Get-ADUser $User | Move-ADObject -TargetPath "OU=schoolname,OU=Users,OU=Student,OU=Year 7,DC=test,DC=com"} What I would like to do from here is introduce 2 new steps into the script, the first would be after the user accounts are created they are then moved into the correct OU. I will have different scripts for each year group so that the path of the OU can be coded into the script. I have used the following line of code in the script Get-ADUser $SAM | Move-ADObject -TargetPath "OU=schoolname,OU=Users,OU=Student,OU=Year 7,DC=test,DC=com" however I receive an error when running the script, if I comment out the line the script works again, the error is as follows Move-ADObject : The operation could not be performed because the object's parent is either uninstantiated or deleted At C:\Users\Administrator\Working Version (before moving user to certain OU).ps1:19 char:23+ Get-ADUser $SAM | Move-ADObject -TargetPath "OU=schoolname,OU=Users,OU=St ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=Test2.User2,CN=Users,DC=test,DC=com:ADUser) [Move-ADObject], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8329,Microsoft.ActiveDirectory.Management.Commands.MoveADObject The second step would be to introduce a check to see if the user account exists before it is created and if it does export the user details of the proposed new account into a csv so that I can manually update the source csv and run the process again. If the user account does not exist then the script should progress and create the accounts. I am assuming this would be done with an if else statement of some sort but I don't know where to begin with it. Any help or advice would be appreciated.. Thanks Noel
gh5000 Posted April 3, 2017 Posted April 3, 2017 This is what I have for checking on existing users. It's not entirely perfect but works for me. It only checks for duplicate usernames, not duplicate people with different usernames (if that's a possibility in your setup). I then use similar to check for duplicate MIS_ID (3rd party field in SIMS that ensures my users are all unique. #Use try cleanly run part of script try{ #If returns true if ad user with username already exists if ([bool] (Get-Aduser -Identity $Username)) { #what happens if true #in your case you could use something like #get-aduser -identity $username -properties * | export-csv c:\csv.csv #that line is untested and off the top of my head!! Write-Warning -Message "User ${username} already exists. Please exit the script" Start-Sleep 999999 Exit } } catch { Write-Host "User hasn't been created yet: Continuing" -ForegroundColor green }
gh5000 Posted April 3, 2017 Posted April 3, 2017 As for the move-adobject error. Does that line work successfully 30 seconds after that first script has run. My point being sometimes new-aduser runs on DC1 and then you try and run get-aduser and DC1 hasn't fully completed putting that object in AD, or the second command queries DC2 and replication hasn't happened yet. I put in a line of "start-sleep 3" just to give a brief pause Or there's a spelling mistake somewhere and "OU=schoolname,OU=Users,OU=Student,OU=Year 7,DC=test,DC=com" doesn't exist. To be sure you're spelling and getting the right syntax for the OU I always goto AD and right click on the OU and go properties, Attribute editor and copy paste from the distinguishedname field.
gh5000 Posted April 3, 2017 Posted April 3, 2017 Actually you probably just need to change Get-ADUser $User | Move-ADObject .... to Get-ADUser $SAM | Move-ADObject...... If you changed your script to import-module activedirectory $users = Import-Csv .\Userlist-sn.csv ForEach ($User in $Users){ $Displayname = $User.Firstname + "." + $User.Lastname $UserFirstname = $User.Firstname $Lastname = $User.Lastname $OU = $User.OU $SAM = $User.SAM $UPN = $User.Firstname + "." + $User.Lastname + "@test.com" $Description = $User.Description $Password = $User.Password New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName "$SAM" -UserPrincipalName "$UPN" -GivenName "$UserFirstname" -Surname "$Lastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -PasswordNeverExpires $false -Server test.com Write-Host $user Get-ADUser $User } Do you see an error at the Get-ADUser part. What variable is Write-host $user giving you. Is it something that Move-ADObject is going to understand?
noelmm Posted April 3, 2017 Author Posted April 3, 2017 Hi Ghanel, Thanks for the reply. I did try that approach but it still failed. I have been able to get the move process to work all I did was reverse the order that I listed the OU's in the script i.e. started with year group OU then listed parent OU etc. I just need to figure out how I can put the check in to see if the user account already exists or not. Thanks Noel
Duke5A Posted April 6, 2017 Posted April 6, 2017 You don't need to move the user after creation. It can all be done when the user is created with the '-path' directive on the 'New-ADUser' commandlet. You just need to add some logic to determine the path and add it to a string. To check for existing users before attempting the add: Try {$UserExists = Get-ADUser -LDAPFilter "(sAMAccountName=$SAM)"} Catch { Continue } If(!$UserExists){ Try{ New-ADUser -Name $DisplayName -DisplayName $Displayname -SamAccountName $SAM -UserPrincipalName $UPN -GivenName $UserFirstname -Surname $UserLastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -PasswordNeverExpires $false -Path $OU -HomeDirectory $HomeFolder -HomeDrive $HomeDrive -ErrorAction Stop } Catch{ Continue } Else{ #User already exists, do nothing Continue } The above is a snippet from a PS script I wrote to automate student account creation based on exports from our SIS system.
howartp Posted April 6, 2017 Posted April 6, 2017 Was about to post the same as Duke! Mine is: $testcount = (Get-ADUser -filter {name -eq $AcName}).count #Count how many users already have this username - hopefully none! if ($testcount -lt 1) { write-host "Creating user:" $AcName " - " $DisplayName New-ADUser -Name $AcName -DisplayName $DisplayName -GivenName $_.givenName -Surname $_.sn -SamAccountName $AcName -UserPrincipalName $AcName -EmailAddress $_.mail -Path "OU=ParentzGoldForm,DC=scraven,DC=internal" -PasswordNeverExpires $True -AccountPassword (ConvertTo-SecureString $PassWord -AsPlainText -force) -Enabled $True -AccountExpirationDate $Expiry } else { #Already exists - do what you want }
noelmm Posted April 7, 2017 Author Posted April 7, 2017 Hi howart and Due, and Thanks for the help. I was unable to create the user directly in the OU, I was just receiving an error message saying the OU wasn't initialised however moving the user worked. I may go back and have a look as to why I received the error message as it should have worked. Now I need to get the if else statement working and you have both given me a place to start Noel
noelmm Posted April 25, 2017 Author Posted April 25, 2017 Hi everyone,I have been doing a little work on my script with the goal of creating a user directory based on the account name and then applying some permissions to the directory. I have added the following code (see below) into my script and the script works in creating the folder in the test location and assigning the 'students' group full control however it does not add the user into the permissions. I recieve no errors, the script runs as I would expect aprt from it doesn't add the user into the permissions, it's almost like that line is being skipped.I have even entered the account user name manually e.g. test.user2 in place of the $SAM variable as a test however this did not apply the permissions either. Can anyone see what is wrong with the script and how to get it working? I've been scratching my head for a couple of hours with no luck. new-item "c:\users\$SAM" -ItemType Directory $acl = Get-Acl -Path "c:\users\$SAM" $permission = '$SAM', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $permission = 'students', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission $acl.SetAccessRule($rule) $acl | Set-Acl -Path "c:\users\$SAM" Thanks for any help you can offer. Noel
pleach85 Posted April 25, 2017 Posted April 25, 2017 You're overwriting the permission variable containing the SAM permissions with the student permissions before applying it to the folder. I think you will need to create two rules using different variables and add them to your acl using "AddAccessRule" rather than SetAccessRule.
pcstru Posted April 25, 2017 Posted April 25, 2017 Struggling for time to help, below is my code split into a callable function which does work but does rely on some globals (server base dir etc). You should be able to see how permissions are grabbed from the server, cleared down and then the list is built by addAccessRule before the whole list is applied at the end. Exceptions are caught and used to notify the caller what happened. # --------------------------------------------------------------------------- # SetFolderACL # # --------------------------------------------------------------------------- function SetFolderACL { Param ([string]$UserName ) $SetFolderACL = "No Work Done" $tdir = $HomeBase + $UserName Write-Host $tdir try { $acl = Get-Acl $tdir $acl.SetAccessRuleProtection($True, $False) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.RemoveAccessRuleAll($rule) Write-Host "Removed" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("ICTStaff","Read, ListDirectory, ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Write-Host "ICT" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Write-Host "SYSTEM" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Write-Host "Administrators" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( $UserName , "Modify", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Write-Host "User" $acct=New-Object System.Security.Principal.NTAccount($NTDomain, "Administrator") $acl.SetOwner($acct) Write-Host "Owner Set" Set-Acl $tdir $acl $SetFolderACL = "$tdir ACL set OK" Write-Host "ACL Set" } catch [system.Object] { $SetFolderACL = "Error setting $tdir ACL" } $SetFolderACL } # ---------------------------------------------------------------------------
Bedders Posted April 25, 2017 Posted April 25, 2017 Removed as PCStru beat me to it, and the CODE tags wrecked my formatting..
noelmm Posted April 25, 2017 Author Posted April 25, 2017 Thanks all for your quick help. I did think it was to do with inheritance but didn't know what I needed to do to solve the issue. I've now got a starting point that I can use. Thanks Noel
howartp Posted April 25, 2017 Posted April 25, 2017 This is mine which I used last week. ################################################################################### # # $BasePath is the folder in which you want to create a class set # # Copy the FolderMakerBat.bat and FolderMaker.PS1 files to the $BasePath # # Set $BasePath in the script below - Don't forget the \ on the end # # Example $BasePath = "\\server\Share\PAHTest\" # # By default, $AccessMode is "Normal" which gives each student # modify rights to their own folder. They cannot access each others folders. # # If you want students to access (read) each others folders, as well as modify their own, # set $AccessMode to "Public" # # If you want the student to only be able to write (not modify) their folder # set $AccessMode to "WriteOnly" # # Now create FolderMaker.csv with UserID and FullName columns (including header) # and put it in $BasePath folder. # There is a SIMS report that achieves this: Reports > Run Report, Focus > Class, 'FolderMaker IT Support' # # On Svr001, browse to $BasePath and double-click on the FolderMakerBat.bat # ################################################################################### $BasePath = "\\server\Photostore\Intake2012\" $AccessMode = "Normal" ################################################################################### # # Do Not Edit Below Here # ################################################################################### foreach ($student in Import-Csv $($BasePath + "FolderMaker.csv")) { $FolderPath = $BasePath + $student.FullName write-host "Folder: " $FolderPath write-host "FullName: " $Student.FullName write-host "UserID: " $Student.UserID new-item $FolderPath -type directory $acl = Get-Acl $FolderPath $acl.SetAccessRuleProtection($True, $False) $ruleAdmin = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $ruleStaff = New-Object System.Security.AccessControl.FileSystemAccessRule("StaffBoth","Modify", "ContainerInherit, ObjectInherit", "None", "Allow") if ($AccessMode -eq "WriteOnly") { $ruleStudent = New-Object System.Security.AccessControl.FileSystemAccessRule($student.UserID, "Write", "ContainerInherit, ObjectInherit", "None", "Allow") } else { $ruleStudent = New-Object System.Security.AccessControl.FileSystemAccessRule($student.UserID, "Modify", "ContainerInherit, ObjectInherit", "None", "Allow") } $acl.AddAccessRule($ruleAdmin) $acl.AddAccessRule($ruleStaff) $acl.AddAccessRule($ruleStudent) if ($AccessMode -eq "Public") { $rulePublic = New-Object System.Security.AccessControl.FileSystemAccessRule("SCA Students","Read", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rulePublic) } Set-Acl $FolderPath $acl Get-Acl $FolderPath Remove-Variable acl write-host "------------------------------------------------------------------------------------------" } ##SetAccessRuleProtection($True, $False) //BlockInheritance?, CopyWhatsInherited? ##New-Object System.Security.AccessControl.FileSystemAccessRule("UserID","Access","SubInheritance", "Propogation", "AllowDeny")
noelmm Posted April 26, 2017 Author Posted April 26, 2017 Thanks everyone for your help. I now have the script working so that it adds multiple permissions, I'll just need to modify this to fine tune the final permissions. Just for reference the working script is below, i'm sure it could be more elegant but it's working at the moment. My next part of the script is to put an if else loop in so that before any user accounts are created or folders created there is a check to see if identically named users and folders already exist and if they do an an incremental number onto the end of the SAM name. new-item "c:\users\$SAM" -ItemType Directory $acl = Get-Acl -Path "c:\users\$SAM" $permission = $SAM, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $permission2 = 'students', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $permission3 = 'All Years', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission $rule2 = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission2 $rule3 = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission3 $acl.AddAccessRule($rule) $acl.ADDAccessRule($rule2) $acl.ADDAccessRule($rule3) $acl | Set-Acl -Path "c:\users\$SAM" Thanks everyone Noel 1
noelmm Posted April 27, 2017 Author Posted April 27, 2017 (edited) Hi everyone, I have been attempting to create my script now for a couple of weeks and with your help I have been able to get it to a working state that I am happy with, now I need to add an If Else loop so that the script will check if the SAM name is already in use in AD. If the SAM already exists in AD I need the script to determine how many variations of the SAM there is and then create a new SAM with a number incremented onto the end e.g. if a new user account for John Smith was to be created and there was already John.smith then the new account would be john.smith2 or if there were 5 John Smiths the new account would be johm.smith6 etc. If the SAM does not exist within AD then my script as it is now should be executed. The working script I have so far is below, I think (I'm probably wrong) that I can leave this script alone and put it inside the else part of the script and in the If part the new script would be identical excpect it would have a check for the user account until a variation is not used and then use this as the SAM. Hopefully I'm explaining this clearly enough for you to understand. Any help would be appreciated. import-module activedirectory $users = Import-Csv .\Userlist-sn.csv ForEach ($User in $Users) { $Displayname = $User.Firstname + "." + $User.Lastname $UserFirstname = $User.Firstname $Lastname = $User.Lastname $OU = $User.OU $SAM = $User.SAM $UPN = $User.Firstname + "." + $User.Lastname + "@test.com" $Description = $User.Description $Password = $User.Password $Email = $UPN $Company = "companyname" New-ADUser -Name "$Displayname" ` -DisplayName "$Displayname" ` -SamAccountName "$SAM" ` -UserPrincipalName "$UPN" ` -GivenName "$UserFirstname" ` -Surname "$Lastname" ` -Description "$Description" ` -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -PasswordNeverExpires $false ` -Server test.com ` -Email "$Email" ` -Company "$Company" ` -homedrive "u:" -homedirectory \\servername\sharename\$SAM #-homedrive "u:" -homedirectory \\servername\sharename\%username% Get-ADUser $SAM | Move-ADObject -TargetPath "OU=Year 7,OU=Student,OU=Users,OU=companyname,DC=test,DC=com" Add-ADPrincipalGroupMembership $SAM students Add-ADPrincipalGroupMembership $SAM "All Years" # Add-ADPrincipalGroupMembership $SAM - Duplicate this line to add the user into more AD groups new-item "c:\users\$SAM" -ItemType Directory #This line can be replaced with the line below to determine the full unc path of the folder $acl = Get-Acl -Path "c:\users\$SAM" $permission = $SAM, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $permission2 = 'students', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $permission3 = 'All Years', 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow' $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission $rule2 = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission2 $rule3 = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission3 $acl.AddAccessRule($rule) $acl.ADDAccessRule($rule2) $acl.ADDAccessRule($rule3) $acl | Set-Acl -Path "c:\users\$SAM" #new-item "\\servername\sharename\foldername" -ItemType Directory } I know that I need to use an if else statement that loops for each of the users in the csv being imported however I have looked at examples and they are a little confusing. Just to clarify the work flow should look like this 1) import csv 2) determine if the SAM variable already exists in AD 3) If SAM variable does exist in AD then a unique SAM name should be created and used 4) If SAM variable does not exists in AD continue with script Any help would be appreciated with this Thanks Noel Edited April 27, 2017 by noelmm
pleach85 Posted April 27, 2017 Posted April 27, 2017 (edited) $i = 1 while((Get-ADUser -Filter {sAMAccountName -eq $SAM}) -ne $null){ $SAM = $SAM + $i.ToString() $i++ } If you place this just after you set your variables from the csv and before the New-ADUser command it should do what you want. Then you don't need an if else with lots of duplicated code in it, much cleaner. Edited April 27, 2017 by pleach85
noelmm Posted April 27, 2017 Author Posted April 27, 2017 (edited) Hi Pleach85, Thanks for the reply. I have done what you said and used your code and it sort of works however it fails on some parts. If no users already exist with the same SAM then everything runs as normal. If existing users with a matching SAM are found a user is not created with the modified SAM name however a folder is created without the user being added into the permissions, this makes sense as the user account is not actually being created. I don't know why your code would work only for part of the script as it looks like it should apply to all of it. If I run the script when I know there will be existing accounts as a test this is the error I receive New-ADUser : The operation failed because UPN value provided for addition/modification is not unique forest-wide At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:65 char:5 + New-ADUser -Name "$Displayname" ` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=Test2.User2,CN=Users,DC=test,DC=com:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8648,Microsoft.ActiveDirectory.Management.Commands.NewADUser Get-ADUser : Cannot find an object with identity: 'Test2.User21' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:89 char:5 + Get-ADUser $SAM | Move-ADObject -TargetPath "OU=Year 7,OU=Student,OU=Users,O ... + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test2.User21:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'Test2.User21' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:91 char:5 + Add-ADPrincipalGroupMembership $SAM students + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test2.User21:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'Test2.User21' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:92 char:5 + Add-ADPrincipalGroupMembership $SAM "All Years" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test2.User21:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership Directory: C:\users Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 27/04/2017 14:17 Test2.User21 Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated." At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:126 char:5 + $acl.AddAccessRule($rule) + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : IdentityNotMappedException New-ADUser : The operation failed because UPN value provided for addition/modification is not unique forest-wide At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:65 char:5 + New-ADUser -Name "$Displayname" ` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=Test3.User3,CN=Users,DC=test,DC=com:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8648,Microsoft.ActiveDirectory.Management.Commands.NewADUser Get-ADUser : Cannot find an object with identity: 'Test3.User31' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:89 char:5 + Get-ADUser $SAM | Move-ADObject -TargetPath "OU=Year 7,OU=Student,OU=Users,O ... + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test3.User31:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'Test3.User31' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:91 char:5 + Add-ADPrincipalGroupMembership $SAM students + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test3.User31:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'Test3.User31' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:92 char:5 + Add-ADPrincipalGroupMembership $SAM "All Years" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Test3.User31:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership d---- 27/04/2017 14:17 Test3.User31 Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated." At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:126 char:5 + $acl.AddAccessRule($rule) + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : IdentityNotMappedException New-ADUser : The operation failed because UPN value provided for addition/modification is not unique forest-wide At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:65 char:5 + New-ADUser -Name "$Displayname" ` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=noel.maloney,CN=Users,DC=test,DC=com:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8648,Microsoft.ActiveDirectory.Management.Commands.NewADUser Get-ADUser : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:89 char:5 + Get-ADUser $SAM | Move-ADObject -TargetPath "OU=Year 7,OU=Student,OU=Users,O ... + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:91 char:5 + Add-ADPrincipalGroupMembership $SAM students + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:92 char:5 + Add-ADPrincipalGroupMembership $SAM "All Years" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership new-item : An item with the specified name C:\users\noel.maloney1 already exists. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:114 char:5 + new-item "c:\users\$SAM" -ItemType Directory #This line can be replaced with ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (C:\users\noel.maloney1:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated." At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:126 char:5 + $acl.AddAccessRule($rule) + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : IdentityNotMappedException New-ADUser : The operation failed because UPN value provided for addition/modification is not unique forest-wide At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:65 char:5 + New-ADUser -Name "$Displayname" ` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=noel.maloney,CN=Users,DC=test,DC=com:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8648,Microsoft.ActiveDirectory.Management.Commands.NewADUser Get-ADUser : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:89 char:5 + Get-ADUser $SAM | Move-ADObject -TargetPath "OU=Year 7,OU=Student,OU=Users,O ... + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:91 char:5 + Add-ADPrincipalGroupMembership $SAM students + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'noel.maloney1' under: 'DC=test,DC=com'. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:92 char:5 + Add-ADPrincipalGroupMembership $SAM "All Years" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (noel.maloney1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMembership new-item : An item with the specified name C:\users\noel.maloney1 already exists. At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:114 char:5 + new-item "c:\users\$SAM" -ItemType Directory #This line can be replaced with ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (C:\users\noel.maloney1:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated." At D:\V13 - As previous version plus folder creation with Multiple Permissions applied and check for existing account.ps1:126 char:5 + $acl.AddAccessRule($rule) + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : IdentityNotMappedException Thanks for your help with this. Noel Edited April 27, 2017 by noelmm
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now