New-ADServiceAccount Powershell script is not working - powershell

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
}

Related

How to specific OU automatticaly for new user in AD?

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

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

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
}

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.