How to specific OU automatticaly for new user in AD? - powershell

Import-Module ActiveDirectory
$firstname = Read-Host -Prompt "Please write firstname"
$lastname = Read-Host -Prompt "Please write lastname"
$SearchBase = "DC=Domain,DC=com"
$OUList = Get-ADOrganizationalUnit -SearchBase $SearchBase -Filter * -Properties Name,DistinguishedName | Select-Object -Property Name,DistinguishedName
$OU = $OUList | Out-GridView -Title "Select OU and Click OK" -OutputMode Single
#Create the AD User
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-UserPrincipalName "$firstname.$lastname".ToLower() `
-AccountPassword (ConvertTo-SecureString "Customs1!" -AsPlainText -Force) `
-Path $OU `
-ChangePasswordAtLogon 1 `
-Enabled 1 `
-DisplayName "$firstname $lastname" `
-SamAccountName "$firstname.$lastname".ToLower()
$timer = [diagnostics.stopwatch]::startnew()
$erroractionpreference = "silentlycontinue"
$mailboxsuccess = $false
while (($timer.elapsed.totalseconds -lt 900) -and (!($mailboxsuccess)))
{
$error.clear()
Enable-Mailbox -Identity $username -Alias $username -Database $mailboxdatabase
`your text`
if($error.count -eq 0)
{
write-host "Mailbox successfully created"
$mailboxsuccess = $true
}
else
{
write-host "." -nonewline
start-sleep -s 30
}
}
$timer.stop()
$erroractionpreference = "continue"
$secs = "{0:N2}" -f ($timer.elapsed.totalseconds)
write-host "Process ran for: $secs seconds."
I try to create an user in specific OU automatically with grid table where I select an OU and click ok, but my program doesn't work, after run appear this.
Please write firstname: Test1
Please write lastname: Test2
....
I need help, thank you.
So far I managed to create a user in a specific OU manually, but I don't want this, I want in automatically mode, I don't know how...

Related

ADSI not validating correctly?

I have a CSV with 1500+ users there are 30 users per class OU, and then 6 class OU's per Intake OU. What I'm trying to achieve is, foreach (user in CSV), check if OU exists, then check if parent OU exists, create the parent OU only if it doesn't exist, then create the OU, then create the user, or just create the user if the OU exists.
Here is the code I'm using:
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
$CSV = Import-Csv "C:\Scripts\AddPupils.csv"
foreach ($user in $CSV) {
# Variables
$GivenName = $user.GivenName
$SurName = $user.SurName
$UserName = $user.UserName
$Class = $user.YearClass
$Intake = $user.Intake
$DisplayName = $GivenName+" "+$SurName
# Create User
$UserOUParent = "OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$UserOU = "OU=Class "+$Class.Substring(1,1)+",OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$NewUserOUParentCheck = [ADSI]::Exists("LDAP://$UserOUParent")
$NewUserOUCheck = [ADSI]::Exists("LDAP://$UserOU")
if ($NewUserOUCheck -eq $false){
if ($NewUserOUParentCheck -eq $false){
"Create Parent Ou"
New-ADOrganizationalUnit `
-Name ("Year "+$Intake+" Intake") `
-Path "OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"Create OU"
New-ADOrganizationalUnit `
-Name ("Class "+$Class.Substring(1,1)) `
-Path ("OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProtectedFromAccidentalDeletion $False
}
"Create User"
New-ADUser `
-Name $DisplayName `
-SurName $SurName `
-GivenName $GivenName `
-DisplayName $DisplayName `
-SamAccountName $UserName `
-UserPrincipalName ($UserName+"#Zulbag.com") `
-AccountPassword (ConvertTo-SecureString "Testing123" -AsPlainText -force) `
-CannotChangePassword $true `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-EmailAddress ($UserName+"#Zulbag.com") `
-Country "GB" `
-Path ("OU=Class "+$Class.Substring(1,1)+",OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProfilePath ("D:\Shares\User Accounts\Students\Intake Year "+$Intake+"\Class "+$Class.Substring(1,1)+"\Profiles\"+$DisplayName) `
-Enabled $true
Start-Sleep -Seconds 5
# Add To Group
$Group = "CN=Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)+",OU=Intake "+$Intake+",OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$GroupOU = "OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$NewGroupCheck = [ADSI]::Exists("LDAP://$Group")
$NewGroupOUCheck = [ADSI]::Exists("LDAP://$GroupOU")
if ($NewGroupCheck -eq $false) {
if ($NewGroupOUCheck -eq $false) {
"Create OU"
New-ADOrganizationalUnit `
-Name ("Intake "+$Intake) `
-Path "OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"create Group"
New-ADGroup `
-Name ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) `
-GroupScope "Global" `
-Path ("OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com")
}
"Add Member"
Add-ADGroupMember ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) $UserName
}
pause
Sample CSV:
GivenName,SurName,Class,UserName,Intake
Ali,Grisdale,1B,AGris,2016
Ayomiposi,Olayera,1B,AOlay,2016
In tests with Write-Output, the [ADSI] validates correctly but it appears to be validating it incorrectly here, the error message I keep getting is:
New-ADOrganizationalUnit : An attempt was made to add an object to the
directory with a name that is already in use
At C:\Scripts\AddPupils-Afzal.ps1:24 char:13
+ New-ADOrganizationalUnit
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Year 2016 In...C=Zulbag,DC=Com:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8305,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnitdirectory
It successfully creates the parent OU, class OU and user, but fails to create the second user, instead validates the OU incorrectly again.
Any Ideas?
Check the script for path errors!

How to add multiple users in to multiple groups in a new users script?

I have a script which is making active directory users, and it's working great.
Here a thing, i need that these users will add them self after the creation to
some groups.
So i've figured out that thre is a cmdle Add-ADPrincipalGroupMembership
but I don't know how to combine this CmdLet into my script ( i'm on PowerShell abit more the a month)
i've tried to use another foreach statement but it didn't worked
Here is the Code:
cls
#get the csv file
$filepath = import-csv "C:\users.csv"
#set the variable for the uers
$newusers = $filepath
#set Passwords for new users
$securepassword = ConvertTo-SecureString "blahblah" -AsPlainText -Force
#start the loop
foreach ($user in $newusers) {
#get user information
$firstname = $user.'First Name'.Trim()
$lastname = $user.'Last Name'.Trim()
$loginname= $user.SamAccountName
$UsrPrincipalName = $user.UserPrincipalName
$jobtitle = $user.'Job Title'
$Department= $user.Department
$Description = $user.Description
$OuPath= $user.Path
$LoginScript=$user.ScriptPath
$displayname= $user.DisplayName
#create the users in active directory
$vars = #{
Name = "$firstname $lastname"
GivenName = $firstname
Surname = $lastname
UserPrincipalName = $UsrPrincipalName
SamAccountName = $loginname
Path = $OuPath
ScriptPath = $LoginScript
AccountPassword = $securepassword
ChangePasswordAtLogon = $false
Department = $Department
DisplayName = $displayname
Description = $Description
Title = $jobtitle
Enabled = $true
}
#Editors comment: Make a hashtable and use splatting when specifying lots of parameters
$newcreatedusers = New-ADUser #vars -PassThru
#starting a loop for adding the users to the groups
Write-Host "`n"
Write-Host "The account for $firstname $lastname created in $OuPath successfully"
}
$filepath = $Adgroups
foreach ($group in $Adgroups){
$adgroup = $group.Groups.splite(',')
Add-ADPrincipalGroupMembership -Identity $group.Groups -members $SamAccountName
}
the CSV file:
after a long "play around" this is the code which creates new users and add them to multiple groups from a CSV file:
cls
#get the csv file
$filepath = import-csv "C:\users.csv"
#set the variable for the uers
$newusers = $filepath
#set Passwords for new users
$securepassword = ConvertTo-SecureString "blahblah" -AsPlainText -Force
#start the loop for adding users
foreach ($user in $newusers) {
#Get user information
$firstname = $user.'First Name'.Trim()
$lastname = $user.'Last Name'.Trim()
#The "SamAccountName" is for the Pre windows 2000 login name has to be less than 20 characters
$loginname= $user.SamAccountName
#The "UserPrincipalname" is the regular login username
$UsrPrincipalName = $user.UserPrincipalName
$jobtitle = $user.'Job Title'
$Department= $user.Department
$Description = $user.Description
$OuPath= $user.Path
$LoginScript=$user.ScriptPath
$displayname= $user.DisplayName
#Get Groups information
$group1 = $user.Group1
$group2 = $user.Group2
$group3 = $user.Group3
$group4 = $user.Group4
#Creat the users in active directory
New-ADUser -Name "$firstname $lastname" -GivenName $firstname `
`
-Surname $lastname -UserPrincipalName $UsrPrincipalName `
`
-SamAccountName $loginname -Path $OuPath -ScriptPath $LoginScript `
`
-AccountPassword $securepassword -ChangePasswordAtLogon $false `
`
-Department $Department -DisplayName $displayname `
`
-Description $Description -Title $jobtitle -Enabled $true
#Add the users in to Groups
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group1
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group2
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group3
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group4
Write-Host "`n"
Write-Host "The account for $firstname $lastname created in $OuPath successfully"
}

Move AD User using powershell

I know I can move an AD user using powershell. What i want to accomplish is moving a bunch of users based on their description. I have a csv file and in that csv their is a year of graduation column. I want all users that have a YOG from 2016 to 2022 moved to the High School OU.
I haven't tried writing the code yet. I was successful in powershell of grabbing user accounts based on dept but not description. Here is a some same data
"ID","FNAME","LNAME","BDATE","GRD","SCHID"
"111111","TEst","student1","19980601","2016","1480"
"222222","test","Student2","19980522","2017","1480"
"333333","test","Student3","19970813","2025","1479"
I've gone ahead and added the schoolcode to the csv file. I think this will be a lot easier to move the students to the correct ou based on this file. 1480 being elem, 1479 hs. Also here is the code I'm using toe create the AD accounts.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv userimport.csv
#Store report in log file in the $log variable
$log = "log.txt"
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.ID
$Password = $User.BDATE
$Firstname = $User.FNAME
$Lastname = $User.LNAME
$Department = $User.GRD
$Company = $User.SCHID #This field refers to the OU the user account is to be moved to
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
"Processing started (on " + $date + "): " | Out-File $log -append
"--------------------------------------------" | Out-File $log -append
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#clasd.net" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Department "$Department" `
-Company "$Company" `
-EmailAddress "$Username#clasd.net" `
-Surname $Lastname `
-Enabled $True `
-Scriptpath "login.vbs" `
-DisplayName "$Firstname $Lastname" `
-Path "ou=users,ou=hs,dc=clasd,dc=net" `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
-ChangePasswordAtLogon $true
# Add User to Groups
#Add-ADPrincipalGroupMembership -Identity $Username -MemberOf "Elem","Elem Students"
Start-Sleep 3
# Move Users to appropiate OU based on School Code
$usr = import-csv userimport.csv
foreach ($User in $usr) {
if ($user.grd -in 2016){
Get-ADUser $User.ID | Move-ADObject -TargetPath 'OU=users,ou=hs,dc=clasd,dc=net'
}
}
}
}
As their AD Username is unique and already contained in your CSV, it's simply a case of checking if the GRD field is in the range 2016-2022 and then moving the account using the ID field:
$filepath = "C:\path\to\data.csv"
$csv = Import-CSV $filepath
foreach ($user in $csv) {
if ($user.GRD -in 2016..2022) {
Get-ADUser $user.ID | Move-ADObject -TargetPath 'OU=High School,DC=domain,Dc=com'
}
}
EDIT: Didn't see your comment that YOG is the Description field, and I've used GRD instead, let me know if this isn't correct?
EDIT2: My answer above would be run after every account is created not during your existing script, it is more efficient to put the account in the correct OU at creation like so:
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.ID
$Password = $User.BDATE
$Firstname = $User.FNAME
$Lastname = $User.LNAME
$Department = $User.GRD
$Company = $User.SCHID #This field refers to the OU the user account is to be moved to
# Choose OU
Switch ($Department)
{
"2016" {$OU = 'OU=users,ou=hs,dc=clasd,dc=net'}
"2017" {$OU = 'OU=2017,OU=users,ou=hs,dc=clasd,dc=net'}
}
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
"Processing started (on " + $date + "): " | Out-File $log -append
"--------------------------------------------" | Out-File $log -append
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#clasd.net" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Department "$Department" `
-Company "$Company" `
-EmailAddress "$Username#clasd.net" `
-Surname $Lastname `
-Enabled $True `
-Scriptpath "login.vbs" `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
-ChangePasswordAtLogon $true
# Add User to Groups
#Add-ADPrincipalGroupMembership -Identity $Username -MemberOf "Elem","Elem Students"
Start-Sleep 3
}
}

Adding User to Multiple Security Groups

I've been able to add a user to one group using the below code.
Get-Aduser -filter 'company -eq "1480"' | %{Add-ADGroupMember "HS Students" $_.SamAccountName}
I want to add the user to multiple groups though. HS and HS Students.
Any help would be appreciated.
EDIT 1
so adding to the bottom of my create user script gives me the messages that the user is already part of the groups I'm trying to add to. Any reason why that is happening.
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.ID
$Password = $User.BDATE
$Firstname = $User.FNAME
$Lastname = $User.LNAME
$Department = $User.GRD
$Company = $User.SCHID #This field refers to the OU the user account is to be moved to
# Choose OU
Switch ($Company)
{
"1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
"1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
}
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
"Processing started (on " + $date + "): " | Out-File $log -append
"--------------------------------------------" | Out-File $log -append
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#clasd.net" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Department "$Department" `
-Company "$Company" `
-EmailAddress "$Username#clasd.net" `
-Surname $Lastname `
-Enabled $True `
-Scriptpath "login.vbs" `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
-ChangePasswordAtLogon $true
#Start-Sleep 5
# Add User to Groups
Get-Aduser -filter 'company -eq "1480"' | % { Add-ADGroupMember "HS Students" $_.SamAccountName; Add-ADGroupMember "HS" $_.SamAccountName }
}
}
So you would need to add a ; after the first command.
Get-Aduser -filter 'company -eq "1480"' | %
{ Add-ADGroupMember "HS Students" $_.SamAccountName; Add-ADGroupMember "HS" $_.SamAccountName }
You could use that as a 1 liner, if you really want, its just looking nicer the way I formatted it.

Why am I getting a "missing expression" error in my PS New-ADUser script?

The error I'm getting is "Missing expression after unary operator '-'" At line 63, char 14. So it's where the Path/OU is set, but I can't find anything wrong with it. Any help is appreciated. Thanks.
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\ADMaint\NewUsers\NewUsers.csv
$Password = "Welcome01"
$OU = "ou=NewUsers,ou=Users,ou=Logins,dc=company,dc=com"
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Firstname = $User.firstname
$Middle = $User.middle
$Lastname = $User.lastname
$Department = $User.department
$Title = $User.title
$Office = $User.office
$Address = $User.address
$Company = $User.company
$employeeNumber = $User.employeeNumber
$employeeID = $User.employeeID
$Telephone = $User.telephone
$Pager = $User.pager
$Mobile = $User.mobile
$Fax = $User.fax
$Custom1 = $User.custom1
$Custom2 = $User.custom2
$Custom3 = $User.custom3
$Custom4 = $User.custom4
$DisplayName = "$Lastname" + ", " + "$Firstname" + " " + "$Middle"
$Username = "$lastname".ToLower() + "$firstname".substring(0,1).ToLower()
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#vinfen.org" `
-Name $DisplayName `
-GivenName $Firstname `
-surname $Lastname `
-initials $Middle `
-department $Department `
-title $Title `
-Office $Office `
-streetAddress $Address `
-Company $Company `
-employeeNumber $EmployeeNumber `
-employeeID $EmployeeID `
-OfficePhone $Telephone `
-mobile $Mobile `
-fax $Fax `
-DisplayName $DisplayName`
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
#-OtherAttribute #{pager="$(User."pager")"; extensionAttribute1="$(User."custom1")"; extensionAttribute2="$(User."custom2")"; extensionAttribute3="$(User."custom3")"; extensionAttribute4="$(User."custom4")"} `
-ChangePasswordAtLogon $true `
-Enabled $true `
}
}
Can't verify now, but looks like there is a missing space before the ` on the previous line.
-DisplayName $DisplayName`
Multi-line commands require the space before the ` symbol.