Add a command at the end of the PowerShell script - powershell

I have a script that adds user to Active Directory
Import-Module activedirectory
$ADUsers = Import-csv E:\src\userlist.csv
foreach ($User in $ADUsers)
{
$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
$email = $User.email
$streetaddress = $User.streetaddress
$city = $User.city
$postalcode = $User.postalcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
# check if user already existe
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "The $Username already exist."
}
else
{
#create user account in the good $OU from the csv
New-ADUser -SamAccountName $Username -UserPrincipalName "$Username#" -Name "$Firstname $Lastname" -GivenName $Firstname -Surname $Lastname -Enabled $True -DisplayName "$Lastname, $Firstname" -Path $OU -City $city -Company $company -State $state -StreetAddress $streetaddress -OfficePhone $telephone -EmailAddress $email -Title $jobtitle -Department $department -postalcode $postalcode -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $false
}
}
In the same script, I want also to have the New-ADUser command that will add the proxy address mail as below:
Set-ADUser -Identity $Username -EmailAddress $email -add {ProxyAddresses="smtp:$email"}
How can I add New-ADUser to my script?

To avoid having to create so many variables from the CSV first and mainly to not having to use the backticks in your code, I would suggest you switch to using Splatting to make the code more readable and maintainable.
You can add the proxyAddresses attribute with the New-ADUSer cmdlet using the OtherAttributes parameter, OR use Set-ADUser to add this after creating the user.
The proxyAddresses attribute is an array of strongly typed strings. That means you cannot use a 'normal' array (Object[]), because in there you can have all kind of value types, not just strings. This is why the code below casts the SMTP email address to [string[]].
I'm assuming the email address to add should be the Primary email address, so that is why I use SMTP: (all caps).
Import-Csv -Path 'E:\src\userlist.csv' | ForEach-Object {
# the '$_' automatic variable holds one record from the CSV
# for convenience create these two variables
$accountName = $_.username
# the proxyAddresses attribute is an array of STRONGLY typed strings
$proxyAddresses = [string[]]"SMTP:$($_.email)"
# check if user already exists
if (Get-ADUser -Filter "SamAccountName -eq '$accountName'") {
Write-Warning "The $accountName already exist."
}
else {
# lire les variables de chaque champs et les assigner en variables de commandes
# use Splatting
$userParams = #{
SamAccountName = $accountName
UserPrincipalName = "$accountName#yourdomain.com"
Name = '{0} {1}' -f $_.firstname, $_.lastname
DisplayName = '{0}, {1}' -f $_.lastname, $_.firstname
GivenName = $_.firstname
Surname = $_.lastname
Enabled = $true
Path = $_.ou
City = $_.city
Company = $_.company
State = $_.state
StreetAddress = $_.streetaddress
OfficePhone = $_.telephone
EmailAddress = $_.email
Title = $_.jobtitle
Department = $_.department
PostalCode = $_.postalcode
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $false
# either add the proxyAddresses here, or do it AFTER creating the new user with
# Set-ADUser -Identity $accountName -Add #{'proxyAddresses' = $proxyAddresses}
OtherAttributes = #{'proxyAddresses' = $proxyAddresses}
}
#create user account in the good $OU from the csv
New-ADUser #userParams
}
}
Hope this helps

Related

Mass add users AD with Powershell

Import-Module ActiveDirectory
$file = "C:\Users\Administrator\Documents\UsersHR.csv"
$targetDN = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$importedUsers = Import-Csv $file
foreach ($user in $importedUsers)
{
$Username = $User.Username
$Password = $User.Password
$Firstname = $User.Firstname
$Lastname = $User.Surname
$Name = $User.Firstname + $User.Lastname
$OU = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$company = $User.company
$department = $User.department
$Password = $User.Password
New-ADUser -SamAccountName $Username -Name $Name -GivenName $Firstname -Surname $Lastname -Enabled $true -DisplayName "$Lastname, $Firstname" -Path $OU -Company $Company -Department $department -AccountPassword $Password -ChangePasswordAtLogon $true
}
I'm working on a VM of windows server 2016.
I'm trying to add several users at once to the AD using PowerShell ISE, but I'm running into several errors about the name.
it's either not properly formed, empty or it's asking for it manually
You didn't say what it's complaining about, but I assume it's this:
$Username = $User.Username
...
New-ADUser -SamAccountName $Username
There are several User Naming Attributes in Active Directory. The sAMAccountName attribute is a short username. It must be 20 characters or less. Although the # character is technically allowed, it is usually never used. In fact, AD Users and Computers won't let you put an # in it.
That "Username" you have in your file is a better fit for the userPrincipalName attribute.
But you will still have to figure something out for the sAMAccountName. Our organization uses the last name (cropped at 18 characters) and first two letters of the first name. That would look something like this:
Import-Module ActiveDirectory
$file = "C:\Users\Administrator\Documents\UsersHR.csv"
$targetDN = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$importedUsers = Import-Csv $file
foreach ($user in $importedUsers)
{
$SamAccountName = "$($User.Surname.Substring(0, [System.Math]::Min(18, $User.Surname.Length)))$($User.Firstname)"
$UserPrincipalName = $User.Username
$Password = $User.Password
$Firstname = $User.Firstname
$Lastname = $User.Surname
$Name = "$($User.Firstname) $($User.Surname)"
$OU = "OU=HR,OU=NTTLab,DC=NTTLab,DC=internal"
$company = $User.company
$department = $User.department
$Password = $User.Password
New-ADUser -SamAccountName $SamAccountName -UserPrincipalName $UserPrincipalName -Name $Name -GivenName $Firstname -Surname $Lastname -Enabled $true -DisplayName "$Lastname, $Firstname" -Path $OU -Company $Company -Department $department -AccountPassword $Password -ChangePasswordAtLogon $true
}
I also fixed how you defined $Name, since it didn't have a space, and you were using $User.Lastname instead of $User.Surname.

New-ADUser OtherAttributes var from CSV

I'm using the powershell script below to create new AD accounts from a CSV file. I recently added the vars for $extensionAttribute1 and $extensionAttribute2. I also added the following -OtherAttributes = #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
How can I correct for the following error?
New-ADUser : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value. At D:\OneDrive\Element Care\Powershell\SACRequest - Create Accounts via CSV.ps1:62 char:30 + ... -OtherAttributes #{'extensionAttribute1' = $extensionAttribute1}
ps script is as follows:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "\\server\path\file.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.'First Name:'
$Lastname = $User.'Last Name:'
$OU = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
$Descritpion = $User.'Account Type'
$company = $User.'Employer:'
$extensionAttribute1 = $User."Submitter Name" # The employee who originally submitted the request.
$extensionAttribute2 = $User."Submitter email" # The email for who originally submitted the request.
# $email = $User.email
# $streetaddress = $User.streetaddress
# $city = $User.city
# $zipcode = $User.zipcode
# $state = $User.state
# $country = $User.country
# $telephone = $User.telephone
# $jobtitle = $User.jobtitle
# $department = $User.department
#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#domain.com" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-City $city `
-Company $company `
-State $state `
-StreetAddress $streetaddress `
-OfficePhone $telephone `
-EmailAddress $email `
-Title $jobtitle `
-Department $department `
-Description $Descritpion `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
}
}
The error you recieved came IMO from the typo's you have made in the original code. Apart from that, I would advice you to use Splatting for cmdlets like New-ADUser that can have a lot of parameters. That way you keep the code both readable and maintainable, and you don't need to use the easily overlooked backtick character for line continuation.
Provided your CSV contains all of the values and all column headers are as shown in your code, something like this should work:
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory
#Store the data from ADUsers.csv in the $ADUsers variable
Import-csv "\\server\path\file.csv" | ForEach-Object {
#Check to see if the user already exists in AD
if ((Get-ADUser -Filter "SamAccountName -eq '$($_.username)'" -ErrorAction SilentlyContinue)) {
#If user does exist, give a warning
Write-Warning "A user account with username $($_.username) already exist in Active Directory."
continue
}
# only store these in variables as they are used in multiple properties
$firstName = $_.'First Name:'
$lastName = $_.'Last Name:'
# create a Hashtable with all properties you want to set for the new user
$properties = #{
'SamAccountName' = $_.username
'UserPrincipalName' = '{0}#domain.com' -f $_.username
'Name' = '{0} {1}' -f $firstName, $lastName
'GivenName' = $firstName
'Surname' = $lastName
'Enabled' = $true
'DisplayName' = '{0}, {1}' -f $lastName, $firstName
'Path' = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
'City' = $_.city
'Company' = $_.'Employer:'
'State' = $_.state
'StreetAddress' = $_.streetaddress
'OfficePhone' = $_.telephone
'EmailAddress' = $_.email
'Title' = $_.jobtitle
'Department' = $_.department
'Description' = $_.'Account Type'
'AccountPassword' = (ConvertTo-SecureString $_.password -AsPlainText -Force)
'ChangePasswordAtLogon' = $true
'OtherAttributes' = #{'extensionAttribute1' = $_.'Submitter Name';'extensionAttribute2'= $_.'Submitter email'}
# you can comment out any properties you do not need or are missing in the CSV
# 'PostalCode' = $_.zipcode
# 'Country' = $_.country
}
# create the new user using the properties Hashtable (splat)
Write-Host "Creating user $($_.username)"
New-ADUser #properties
}

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

Creating ad user account with distinguished name

For the life of me, I can't figure a way to either create a new ad account with the distinguished name as firstname lastname instead of the username or modifying it afterwards.
New-ADUser -SamAccountName $UserName -Name $UserName -DisplayName $DisplayName -GivenName $FirstName -Surname $LastName -UserPrincipalName $MailAddress -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $false -Path $OU -ChangePasswordAtLogon $true -server ad.corp.com -MobilePhone $MobileNumber -OfficePhone $OfficeNumber -Title $JobTitle
$fullname = $FirstName + " " + $LastName
$distinguishedName="CN=" + $fullname + ", " + $ou
set-aduser $distinguishedName
The set-aduser returns a "directory not found" which makes sense since the distinguished name is the username.
Thanks
You can assign your newly created ADUser to a variable and set its name as follows:
$Params = #{
SamAccountName = $UserName
Name = $UserName
DisplayName = $DisplayName
GivenName = $FirstName
Surname = $LastName
UserPrincipalName = $MailAddress
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
Enabled = $False
Path = $OU
ChangePasswordAtLogon = $True
Server = 'ad.corp.com'
MobilePhone = $MobileNumber
OfficePhone = $OfficeNumber
Title = $JobTitle
PassThru = $True
}
$ADUser = New-ADUser #Params
I couldn't test this, but it should work:
$DistinguishedName = "CN=$FirstName $LastName, $OU"
$ADUser.DistinguishedName = $DistinguishedName
I actually got it to work by using the rename-adobject.
Rename-ADObject -Identity $user -NewName $fullname -server ad.corp.com

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.