How to do error handling when creating AD users - powershell

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

Related

New-ADServiceAccount Powershell script is not working

Hi StackOverflow family,
Hope you are well?
I’m facing one issue in the PowerShell script for the last 4 days. I have created/ modified it more than 50 times same script and tested it. every time it is going to catch or get some error. and error is not clear so can't find the cause.
can you help me here?
Thanks
if ($action -like 'create_ad_svc_acc') {
<#
| Set-ADAccountPassword -Identity $svcAccountName -Reset -NewPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
#>
try{
$svcAccountName = "testing_account"
$passwordExp = "no"
$InteractiveLogon = "yes"
#password
$password = "Welcome#1234567890"
#organizational unit
$path = "OU=Service,OU=Accounts,OU=testcompany OU=Administration,DC=domain,DC=internal" #changed the path for company privacy pupose
#Dormant OU
$dormantPath = "OU=Users,OU=Dormant,DC=domain,DC=internal"
#dns host (mandatory)
$dnsHost="test.domain.internal" #changed the host for company privacy pupose
#Set Password expiry
if ($passwordExp -like 'no'){ #environment dependent
$expiryFlag = $True
}
else{
$expiryFlag = $false
}
#create new account
New-ADServiceAccount `
-SamAccountName $svcAccountName `
-name $svcAccountName `
-Enabled $true `
-Path $path `
-DNSHostName $dnsHost `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
sleep 2
if (Get-ADServiceAccount -Identity $svcAccountName){
if ( $InteractiveLogon -like "no"){
Add-ADGroupMember -Identity GBL_DenyLogonLocally -Members $svcAccountName
}
}
Write-Host "Service account has been created"
}
catch{
Write-Warning "There was an error while creating the service account"
}
return
}
As advised in comments, you can display the error by putting the default error output variable in the catch block
When you create an account and want to check it quickly you must query the same domain controller as the one you created it on, else the script can error because it checked another DC but it hadnt yet replicated to that DC
if ($action -like 'create_ad_svc_acc') {
<#
| Set-ADAccountPassword -Identity $svcAccountName -Reset -NewPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
#>
try{
$svcAccountName = "testing_account"
$passwordExp = "no"
$InteractiveLogon = "yes"
#password
$password = "Welcome#1234567890"
#organizational unit
$path = "OU=Service,OU=Accounts,OU=testcompany OU=Administration,DC=domain,DC=internal" #changed the path for company privacy pupose
#Dormant OU
$dormantPath = "OU=Users,OU=Dormant,DC=domain,DC=internal"
#dns host (mandatory)
$dnsHost="test.domain.internal" #changed the host for company privacy pupose
#Set Password expiry
if ($passwordExp -like 'no'){ #environment dependent
$expiryFlag = $True
}
else{
$expiryFlag = $false
}
#create new account
New-ADServiceAccount `
-SamAccountName $svcAccountName `
-name $svcAccountName `
-Enabled $true `
-Path $path `
-DNSHostName $dnsHost `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
sleep 2
### Query the SAME DC we created the account on
if (Get-ADServiceAccount -Identity $svcAccountName -Server $DNSHostname -ErrorAction Stop){
Write-Host "Service account has been created"
if ( $InteractiveLogon -like "no"){
Add-ADGroupMember -Identity GBL_DenyLogonLocally -Members $svcAccountName
}
}
###
}
catch{
Write-Warning "There was an error while creating the service account"
### This var contains the error
$_
###
}
return
}

Directory Object Not Found - Active Directory - Inputting from CSV

hi there im trying to import user accounts from a CSV file to Active Directory but i've been trying for hours to no avail. Basically I have the CSV file i want to import. So I've been trying multiple powershell scripts and getting the same error
CSV contents:
GivenName,Surname,Name,SamAccountName,Path,userPrincipalName
Scooby,Doo,Scooby,Scooby,"OU=Vehicles,OU=Production,DC=csc,DC=local",scooby#csc.local
Shaggy,Rogers,Shaggy,Shaggy,"OU=Vehicles,OU=Production,DC=csc,DC=local",shaggy#csc.local
Fred,Jones,Fred,Fred,"OU=Weapons,OU=Production,DC=csc,DC=local",fred#csc.local
Daphne,Blake,Daphne,Daphne,"OU=Weapons,OU=Production,DC=csc,DC=local",daphne#csc.local
Velma,Dinkley,Velma,Velma,"OU=Weapons,OU=Production,DC=csc,DC=local",velma#csc.local
Pat,Pending,Pat,Pat,"OU=Biological,OU=Research,DC=csc,DC=local",pat#csc.local
Red,Max,Red,Red,"OU=Biological,OU=Research,DC=csc,DC=local",red#csc.local
Peneolope,Pitstop,Peneolope,Peneolope,"OU=Biological,OU=Research,DC=csc,DC=local",peneolope#csc.local
Peter,Perfect,Peter,Peter,"OU=Energy,OU=Research,DC=csc,DC=local",peter#csc.local
Rock,Slag,Rock,Rock,"OU=Energy,OU=Research,DC=csc,DC=local",rock#csc.local
Gravel,Slag,Gravel,Gravel,"OU=Energy,OU=Research,DC=csc,DC=local",gravel#csc.local
Luke,Bear,Luke,Luke,"OU=Energy,OU=Research,DC=csc,DC=local",luke#csc.local
Rufus,Ruffcut,Rufus,Rufus,"OU=Energy,OU=Research,DC=csc,DC=local",rufus#csc.local
Dick,Dastardly,Dick,Dick,"OU=Energy,OU=Research,DC=csc,DC=local",dick#csc.local
Rick,Sanchez,Rick,Rick,"OU=Board,OU=Management,DC=csc,DC=local",rick#csc.local
Morty,Smith,Morty,Morty,"OU=Board,OU=Management,DC=csc,DC=local",morty#csc.local
Beth,Smith,Beth,Beth,"OU=HR,OU=Management,DC=csc,DC=local",beth#csc.local
Powershell Script:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\csc.csv
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, output a warning message
Write-Warning "A user account $Username has already exist in Active Directory."
}
else
{
#If a user does not exist then create a new user account
#Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#csc.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword $Password `
}
}
Output from powershell:
New-ADUser : Directory object not found
At C:\scripts\Add-NewUsers.ps1:24 char:25
+ New-ADUser <<<< `
+ CategoryInfo : ObjectNotFound: (CN=Rick Sanchez...DC=csc,DC=local:String) [New-ADUser], ADIdentityN
undException
+ FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.NewADUser
this error is repeated 7 times or so but the only thing different is the name (where is says ObjectNotFound(CN=Rick Sanchez..) different name for each error
Try adding this try catch block to your code, according to some googling this error is related to the OU where you want to create the new users not existing.
$ErrorActionPreference = 'Stop'
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
try
{
Get-ADOrganizationalUnit $OU
}
catch
{
"Creating OU: $OU"
$name, $path = $OU.Split(',',2)
New-ADOrganizationalUnit -Name $name.Replace('OU=','') -Path $path
}
# Continue script here
}
Unrelated but, you might also want to consider start using splatting on your code for obvious reasons:
$params = #{
SamAccountName = $Username
UserPrincipalName = "$Username#csc.local"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
ChangePasswordAtLogon = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
AccountPassword = $Password
}
New-ADUser #params

Error mapping home directory with a PowerShell script

I'm using a script to create new users and everything is working fine. However, when I try to log in with a user created with this script, I get the following error:
A Problem has occurred and your network home directory is not available.
This may be because a network file server is offline.
You have been logged on with a temporary home drive (H:) which may be shared
with other users.
The script creates the user and applies the correct permissions as far as I can tell.
Here's the script:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv .\Create_Staff_Accounts.csv
#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.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
$group = $User.group
$title = $User.title
$start = $User.start
$Homedrive = "H:"
$UserRoot = "\\servername\st$\"
$HomeDirectory = $UserRoot + $Username
#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 exists 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 `
-Name "$Firstname $Lastname" `
-UserPrincipalName "$($username)#domain.local" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
-Homedrive $Homedrive `
-HomeDirectory $HomeDirectory `
-ScriptPath "logonscript.bat" `
-Description "Staff Account: $($title) from: $($start)"
#-ChangePasswordAtLogon $True `
#Now create the home folder and set modify permissions
Add-ADGroupMember -Identity $group -Members $Username
Add-ADGroupMember -Identity groupname -Members $Username
Add-ADGroupMember -Identity groupname -Members $Username
New-Item -ItemType Directory -Path "\\servername\st$\$($User.username)"
$path = Get-Item -Path "\\servername\st$\$($User.username)"
$acl = (Get-Item $path).GetAccessControl('Access')
$AR = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.SetAccessRule($AR)
Set-Acl -Path $Path -AclObject $acl
}
}
Thank you for your help and support.

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

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.