AD-user script has no output - powershell

I'm creating a script for adding multiple users in Active Directory. I stumbled upon this link, when I couldn't get the guide described in the question to work either. I then tried one of the solutions in the comments
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}
Here is my CSV file
firstname;lastname;username;password;ou
Mette;Frederiksen;MeFr;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Sussi;Hart;SuHa;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Ove;Tylstrup;OvTy;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Karlos;Mondolez;KaMo;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Anne;Otto;AnOt;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Dennis;Ågard;DeÅg;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Helena;Riss;HeRi;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Risa;Lamende;RiLa;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
However, when I run the above code nothing happens
PS C:\Users\RGDAdmin> C:\Users\RGDAdmin\Documents\ADUser.ps1
PS C:\Users\RGDAdmin>
When I add the Delimiter parameter, I get this
Created new user 'KaMo' with initial password: Password1
New-ADUser : The directory service was unable to allocate a relative identifier
At C:\Users\RGDAdmin\Documents\ADUser.ps1:31 char:9
+ New-ADUser #userParams
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Anne Otto,OU...DC=rgd,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId :
ActiveDirectoryServer:8208,Microsoft.ActiveDirectory.Management.Commands.NewADUser
PS. I know the password is bad practice in terms of passwords

Your file is delimited by semicolons, so you will definitely need to specify the -Delimiter parameter. But the documentation has a caveat:
To specify a semicolon (;) enclose it in single quotation marks.
So it should look like this:
$ADUsers = Import-Csv -Delimiter ';' -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
If that still results in that RID error, then there's possibly something wrong on the server. Can you create users manually using AD Users and Computers?

Try reviewing this. I don't have access to ActiveDirectory to test it myself.
#helpers
function usernameIsNotBlank {
[CmdletBinding()]
param(
$Username
)
[regex]$rx = "\S"
return $rx.match($Username)
}
function usernameDoesNotAlreadyExist {
[CmdletBinding()]
param(
$Username
)
$UserDoesNotExist = $true
$UserObject = $(
try {
Get-ADUser $Username
}
catch {
$null
}
)
if ($null -ne $UserObject) {
$UserDoesNotExist = $false
Write-Verbose "$Username already exists"
}
else {
$UserDoesNotExist = $true
}
return $UserDoesNotExist
}
function suppliedUsernameIsAvailable {
[CmdletBinding()]
param(
$Username
)
return ((usernameIsNotBlank -Username $Username) -and (usernameDoesNotAlreadyExist -Username $Username))
}
#script
$OriginalVerbose = $VerbosePreference
$VerbosePreference = "Continue"
Import-Module ActiveDirectory
$CSV = "C:\Users\Desktop\Powershell file\EM-mis-new-AD.csv"
$Data = Import-CSV $CSV
foreach ($Line in $Data) {
if (suppliedUsernameIsAvailable($Line.username)) {
New-ADUser -Name "$Line.firstname $Line.lastname" -GivenName "$Line.firstname" -Surname "$Line.lastname" -SamAccoutnname "$(Line.username)#mydomain.com" -AccountPassword (ConvertTo-SecureString $Line.password -AsPlainText -Force) -ChangePasswordAtLogon $true -Path "$Line.ou"
}
}
$VerbosePreference = $OriginalVerbose

Related

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

New-ADUser : The server is unwilling to process the request

I am using PS to add users to AD using input data from a CSV file, but I keep getting the error:
The code and csv will be attached to this post, any pointers or insight leading to a solution will be appreciated!
Import-Module ActiveDirectory
$ar_user = Import-Csv \\JHanDomain.local\Home\IT\IT_Share\a10\users.csv
foreach ($User in $ar_user)
{
$uname = $User.Username
$pw = $User.Password
$Fname = $User.FirstName
$Lname = $User.LastName
$ou = $User.OUPath
$desc = $User.Description
$action = $User.Action
$splat = #{
Name=$Uname
AccountPassword=(ConvertTo-SecureString $pw -AsPlainText -Force)
GivenName=$Fname
Surname=$Lname
DisplayName="$FName $LName"
Path=$ou
Description=$desc
Enabled=$true
}
if (Get-ADUser -F {AccountName -eq $Uname})
{
Write-Warning "User Already Exists!"
}
else
{
New-ADUser #splat
}
}
users.csv
Edit: The code works when I remove Path=$ou from $splat but I can't identify anything wrong with the path. I've tried switching "cn" for "ou" (in the CSV file) but same results. The path itself is correct.
The problem was with the OUPath in the input data:
cn=Bus_IT,dc=JHanDomain.local,dc=local
changed to
ou=Bus_IT,dc=JHanDomain,dc=local
Everything works

Powershell Active Directory username

For a school project, i need to make a Powershell script, but to create a username, with only the first letter of the person name, and the full second name, could anyone help me with this? This is what i currently have:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
ForEach ($user in $users) {
# Gather the user Information
$fname = $user.FirstName
$lname = $user.LastName
$jtitle = $user.JobTitle
$OUpath = $user.OU
Write-Host $fname
Write-Host $lname
Write-Host $jtitle
Write-Host $OUpath
#Gebruiker aanmaken in AD
New-ADUser -Name "$fname $lname" -GivenName $fname -SamAccountName $lname -Surname $lname -UserPrincipalName "$lname" -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true
}
As per the comments from others. Add this line after $lname = ...
$sam = "{0}$lname" -f $fname.Substring(0,1)
Then edit your New-ADUser line use $sam
New-ADUser .... -SamAccountName $sam ...
Turning my comment into an answer.
You can create the user's SamAccountName quite easily, combining the first character of the users GivenName with the full LastName. However, you need to check that this SamAccountName is not already in use.
Another thing is that the UserPrincipalName should be in the form of <user>#<DNS-domain-name>.
To improve your code also using Splatting:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
foreach ($user in $users) {
# first create the desired SamAccountName for the new user
$accountName = "{0}{1}" -f $user.FirstName.Substring(0,1),$user.LastName
# test if a user with that SamAccountName already exists
$checkUser = Get-ADUser -Filter "SamAccountName -eq '$accountName'" -ErrorAction SilentlyContinue
if ($checkUser) {
Write-Warning "SamAccountName $accountName already used for user $($checkUser.Name)"
}
else {
# create a hashtable with all parameters for the New-ADUser cmdlet
$userParams = #{
Name = "$fname $lname"
GivenName = $user.FirstName
Surname = $user.LastName
Title = $user.JobTitle
SamAccountName = $accountName
Path = $user.OU
AccountPassword = $securePassword
PasswordNeverExpires = $true
Enabled = $true
UserPrincipalName = "$accountName#yourdomain.com" # <-- put YOUR domain here after the '#'
# other parameters go here if needed
}
New-ADUser #userParams
}
}
Also, keep in mind that you cannot use just any character for a SamAccountName.
Characters " [ ] : ; | = + * ? < > / \ , # are illegal, aswell as non-printable characters and the dot . can not be the last character of the name.
AND, the system limits sAMAccountName to 20 characters for user objects.
To make sure, use something like:
$accountName = ($accountName -replace '["\[\]:; |=+\*\?<>/\\,#]').TrimEnd(".") -replace '^(.{1,20}).*', '$1'

Powershell issue with a defined variable

I am pretty new to powershell and have a code that I found. I had it working but now it is no longer working. I didn't change anything with the variable so I am not sure what is going on. Here is a link to a Screenshot of the code and error. Please let me know if you need any other information
https://imgur.com/a/ntEhdoV
Thank you!
Import-Module activedirectory
$ADUsers = Import-csv 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
$Password = $User.Password
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#Mydomain" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname, $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Error:
Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
At C:\Users\jcarnovale\Desktop\Testing if.ps1:22 char:6
if (Get-ADUser -F {SamAccountName -eq $Username})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUse
You probably want to check that you have a good username before proceeding in the script, like:
$Username = $User.username
...
if(!$Username) {
throw "Username was empty!"
}
Also, try changing the Get-ADUser filter to use a string:
if (Get-ADUser -F "SamAccountName -eq $Username")
{
}
You didn't show us anything of the imported CSV file itself and I think the main problem is in there.
Import-Csv by default expects the comma (,) to be used as delimiter character. If that is not the case in your file, you need to add parameter -Delimiter followed by the character that is used as separator in your file (like -Delimiter ';' if your file uses the semicolon).
Please check that first, so the Import-Csv cmdlet can parse the file correctly.
Next, it could be that there are empty values in the username column and if so, the code should skip these rows.
Also, as commented, the -Filter parameter needs a double-quoted string "Property -eq 'something'" in which a variable like $username is expanded, instead of a scriptblock {..}
Finally, I'd recommend using Splatting on cmdlets that take many properties instead of using backticks.
Try
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}

Edit value in CSV using powershell

For a small project, I want to create AD users from a small CSV file. I made jobs (PowerShell scripts) that run every few minutes, to pick-up the user creation based on the status of the user I define in the script. Per example; when a user is created in the AD, I change the status to addmailbox. Then another job will come and add the mailbox.
Everything is going well, but I noticed a bug. The way I am editing the status in the CSV file is wrong, because I change the status for all users in the CSV when I only want to change one. But I can't seem to get any other method working.
#When encountering any error, stop the script.
$ErrorActionPreference = "Stop";
#Check if there is a data file.
$FileExists = Test-Path C:\inetpub\wwwroot\melle\data.csv
if($FileExists -eq $true) {
$Users = Import-Csv -Path "C:\inetpub\wwwroot\melle\data.csv"
foreach ($user in $Users) {
$Status = $User.Status;
$userPrincipalName = $User.userPrincipalName;
$SAMAccountName = $User.SAMAccountName;
$userInstance = $User.userInstance;
$Name = $User.Name;
$displayName = $User.DisplayName;
$Path = '"' + $User.Path + '"';
$GivenName = $User.GivenName;
$Surname = $User.Surname;
$SIP = $userPrincipalName;
if ($Status -eq "CreateUser") {
try {
#create user
Import-Module ActiveDirectory;
New-ADUser -SAMAccountName $SAMAccountName -Instance $userInstance -Name $name -DisplayName $displayName -Path "correct.path.com" -GivenName $givenname -Surname $surname -userPrincipalName $userprincipalname -AccountPassword (ConvertTo-SecureString -String "bla" -AsPlainText -Force) -PassThru | Enable-ADAccount;
#change status
(Get-Content C:\inetpub\wwwroot\melle\data.csv) | Foreach-Object {$_ -replace 'CreateUser','AddMailbox'} | Out-File C:\inetpub\wwwroot\melle\data.csv
#exit on completion
Exit(Write-Host 'User was created in AD.');
} Catch {
#write any errors to error log.
$_ | Out-File C:\inetpub\wwwroot\melle\errors.log -Append;
}
} else {
Exit(Write-Host 'No user with status CreateUser was found.');
}
}
}else {
Exit(Write-Host 'No data.csv file was found.');
}
The way I do it now is (Get-Content C:\inetpub\wwwroot\melle\data.csv) | Foreach-Object {$_ -replace 'CreateUser','AddMailbox'} | Out-File C:\inetpub\wwwroot\melle\data.csv but I want to define it for only the row that the script is talking to in the foreach.
I tried searching for a solution on here and different sites, but I wasn't able to get the solutions others are using to work on my script. Some scripts were too advanced for me to understand.
What would be the correct approach to only change the status for the line I'm working on in the loop?
UPDATE: Solved
Working script:
#Check if there is a data file.
$FileExists = Test-Path C:\inetpub\wwwroot\melle\data.csv
if($FileExists -eq $true) {
$Users = Import-Csv -Path "C:\inetpub\wwwroot\melle\data.csv"
$UsersThatNeedToBeCreated = $Users | Where-Object {$_.Status -eq 'CreateUser'};
# Check that we have users that need to be created, might need fine-tuning.
if($UsersThatNeedToBeCreated -eq $null -or $UsersThatNeedToBeCreated.Count -eq 0){
# Write-Host doesn't have a meaningful return code, so you can separate those lines.
Exit(Write-Host 'No user with status CreateUser was found.');
}else{
# This way it's only run once
Import-Module ActiveDirectory;
}
$Users | ForEach-Object {
if($_.Status -eq 'CreateUser'){
try {
#create user
New-ADUser -SAMAccountName $_.SAMAccountName -Instance "'" + $_.userInstance + "'" -Name $_.name -DisplayName $_.displayName -Path "working.path.here" -GivenName $_.givenname -Surname $_.surname -userPrincipalName $_.userprincipalname -AccountPassword (ConvertTo-SecureString -String "Welcome01" -AsPlainText -Force) -PassThru | Enable-ADAccount;
#change status
$_.Status = 'AddMailbox';
} Catch {
#write any errors to error log.
$_ | Out-File C:\inetpub\wwwroot\melle\errors.log -Append;
}
}
}
$Users | ConvertTo-Csv | Out-File 'C:\inetpub\wwwroot\melle\data.csv'
Exit(Write-Host 'User was created in AD.');
}else {
Exit(Write-Host 'No data.csv file was found.');
}
As you already noticed, your current approach doesn't work. You're grabbing the whole content of the CSV and replace every instance. That Import-Csv statement actually gives you a data structure that allows you to change values. You just need to write it back afterwards.
This approach still is going to be error prone and you will run into issues with it. If I'm understanding you correctly, you want to keep track of the state and have multiple scripts that do different things. Sooner or later you will encounter situations where they overwrite each others changes and/or lock due to competing access requests. If you want to do it this way you should consider using a database that supports row based locking (most probably do). Otherwise you will need to find a way to make them run sequentially or implement row based locking yourself.
That said, one possible solution could look like the following. I haven't run it but the basic structure should be right. An example with this for overwriting changes would be the long time it can take to create a mailbox. As the file is only read at the start of the script and written at the end, it might change in-between.
#When encountering any error, stop the script.
$ErrorActionPreference = "Stop";
#Check if there is a data file.
$FileExists = Test-Path C:\inetpub\wwwroot\melle\data.csv
if($FileExists -eq $true) {
$Users = Import-Csv -Path "C:\inetpub\wwwroot\melle\data.csv"
$UsersThatNeedToBeCreated = $Users | Where-Object {$_.Status -eq 'CreateUser'};
# Check that we have users that need to be created, might need fine-tuning.
if($$UsersThatNeedToBeCreated -eq $null -or $UsersThatNeedToBeCreated.Count -eq 0){
# Write-Host doesn't have a meaningful return code, so you can separate those lines.
Write-Host 'No user with status CreateUser was found.'
Exit;
}else{
# This way it's only run once
Import-Module ActiveDirectory;
}
$Users | ForEach-Object {
$Status = $User.Status;
$userPrincipalName = $User.userPrincipalName;
$SAMAccountName = $User.SAMAccountName;
$userInstance = $User.userInstance;
$Name = $User.Name;
$displayName = $User.DisplayName;
$Path = '"' + $User.Path + '"';
$GivenName = $User.GivenName;
$Surname = $User.Surname;
$SIP = $userPrincipalName;
if($_.Status -eq 'CreateUser'){
try {
#create user
New-ADUser -SAMAccountName $SAMAccountName -Instance $userInstance -Name $name -DisplayName $displayName -Path "correct.path.com" -GivenName $givenname -Surname $surname -userPrincipalName $userprincipalname -AccountPassword (ConvertTo-SecureString -String "bla" -AsPlainText -Force) -PassThru | Enable-ADAccount;
# change status
$_.Status = 'AddMailbox';
} Catch {
# write any errors to error log.
$_ | Out-File C:\inetpub\wwwroot\melle\errors.log -Append;
}
}
}
$Users | ConvertTo-Csv -NoTypeInformation | Out-File 'C:\inetpub\wwwroot\melle\data.csv'
Write-Host 'User was created in AD.'
Exit
}else {
Write-Host 'No data.csv file was found.'
Exit
}