Powershell Instance Parameter - powershell

I am automating the creation of user accounts in our Windows AD. I am trying to copy the permissions from one account to another,(like you would if you right click and copied a user inside of the "Active Directory Users and Computers" application) but when using the cmdlet 'New AD-User' and passing in a variable to the 'instance' parameter, it does nothing different than if I do not pass the variable at all.
This is what I am using to obtain the $userInstance variable:
$userInstance = Get-ADUser -Identity $department User
This is the code I am using to create a new user:
New-ADUser `
-SamAccountName $userName `
-UserPrincipalName "$userName#123.COM" `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-Enabled $true `
-DisplayName "$firstName $lastName" `
-City $city `
-PostalCode $zip `
-Company $company `
-State $state `
-EmailAddress $email `
-Department $department `
-Instance $userInstance `
-AccountPassword (ConvertTo-SecureString "1234" -AsPlainText -Force)
When I run this command, it does the same exact thing as if I ran this command without the instance parameter.
New-ADUser `
-SamAccountName $userName `
-UserPrincipalName "$userName#123.COM" `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-Enabled $true `
-DisplayName "$firstName $lastName" `
-City $city `
-PostalCode $zip `
-Company $company `
-State $state `
-EmailAddress $email `
-Department $department `
-AccountPassword (ConvertTo-SecureString "1234" -AsPlainText -Force)
Am I missing something? I do not understand what the 'instance' parameter is supposed to be doing if it only copies certain attributes that are easily obtainable(state, company, city). Is there something out there that actually copies a template account or do I need to write a loop that goes through every single attribute, permission, and group in the template account that provides some sort of meaning to my organization and assign them manually?

What exactly do you mean by "permission"?
Permissions on resources are set based on the objectSid of a user. Since this is unique to every user you can never "copy" them (and related permissions) to a new user.
Group memberships are stored on groups not on users. The memberOf attribute is just a "backLink" so this won't be copied neither.
Group membership needs to be added in a separate step, e.g. by using
Add-ADGroupMember
cmdlet in PowerShell...

"Permissions" might not have been the word I was looking for necessarily. I wanted to create the user and assign them the same groups and directory location as a previous User. I was able to add group membership to my new users by using the method stated by #Oliver Hauck earlier
Add-ADGroupMember
This aided me in my findings, but what I desired was to not have to write long, repetitive switch code for each new employee type, along with their groups, we could onboard. In hopes that someone sees this and doesn't feel intrigued in writing super long, boring switch code, I wanted to share how I achieved this if it helps anyone else in the future. I still obtained the $userInstance variable in the same way, but adding the -Property parameter defined to MemberOf
$userInstance = Get-ADUser -Identity $department User -Properties MemberOf
I then used the $userInstance variable to obtain the properties I needed from it (Groups to copy, Directory Path)
//Obtains the Path from the copied User, without their common name (CN) attached
$path = $userInstance.DistinguishedName.split(",",2)[-1]
I still created the new user with the same command as above but added the -Path parameter to assign the directory path to the New-ADUser cmd
New-ADUser `
-SamAccountName $userName `
-UserPrincipalName "$userName#123.COM" `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-Enabled $true `
-DisplayName "$firstName $lastName" `
-City $city `
-PostalCode $zip `
-Company $company `
-State $state `
-Path $path `
-EmailAddress $email `
-Department $department `
-AccountPassword (ConvertTo-SecureString "1234" -AsPlainText -Force)
And here is how I obtained and assigned the Group Membership to the New User
//Obtains the groups to be copied from the existing User
$refGroups = $userInstance.MemberOf
//Adds AD Group Membership to User
$refGroups | Add-ADGroupMember -Members $userName

Related

Powershell New-ADUser Password Complexity Exception

I'm trying to mass import AD users from a CSV file. But I keep getting the following error:
The password does not meet the length, complexity, or history requirement of the domain
But the password that's created with $InitialPassword has uppercase, lowercase, numbers and special characters so I don't get what it's not meeting.
ForEach($user in $CSV){
$FirstName = $user.Voornaam
$LastName = $user.Familienaam
$DayOfBirth = $user.geboortedatum
$Enrollment = $user.inschrijvingsjaar
$Classroom = $user.Klas
$PhoneNumber = $user.contactnummer
# create and sanatize username
$UserName = "$($FirstName.ToLower()).$($LastName.ToLower())"
$Username = $UserName.Replace(" ", "")
# generate password
$InitialPassword = (ConvertTo-SecureString "$($FirstName[0])$($LastName.ToLower())$($Enrollment)!" -AsPlainText -Force)
New-ADUser -Name "$FirstName $LastName" `
-GivenName "$FirstName" `
-Surname "$LastName" `
-UserPrincipalName ("{0}#{1}" -f $UserName, "arrow.local") `
-SamAccountName $UserName `
-Initials "$($FirstName[0])$($LastName[0])" `
-DisplayName "$FirstName $LastName" `
-HomePhone $PhoneNumber `
-Description $Classroom `
-Office $Enrollment `
-AccountPassword $InitialPassword `
-Enabled $true
Write-Host "$UserName"
Write-Host "$InitialPassword"
}
The default password complexity rules disallow the account's name or username in the password - so when you compose the password of strings that also go into the Display Name, you're in violation of the complexity requirement!
If you're also seeing errors due to invalid user names, be aware that sAMAccountName attributes must be:
Unique at the forest-level
No more than 20 characters long

Encoding limit exceeded

I have a pretty lengthy script that takes either user input or data from a .csv file to create AD accounts. Not all the time, but sometimes I receive the following error while running it:
New-ADUser : The server has returned the following error: encoding limit exceeded.
Is there a limit on the amount of variables I can use? Because I do have quite a few.. here's what the sample code looks like where it sometimes get stuck:
If($GuardAccount){
If($Clone){
If($Attribute6){
$newuser = New-ADUser -SamAccountName $Username -Enabled $true -Name $DisplayName -Path $Path -AccountPassword $Password `
-GivenName $FirstName -Surname $LastName -Initials $Initials -DisplayName $DisplayName -City $City `
-Company $Company -Department $Department -Country $Country -State $State `
-StreetAddress $Street -PostalCode $Postal -OfficePhone $Telephone -Fax $Fax -Description $Description `
-Title $Title -Office $Office -Instance $Cloneuser -UserPrincipalName "$Username#business.com" -PassThru `
-OtherAttributes #{
'extensionattribute6'=$Attribute6;
}
...
So what does encoding limit exceeded mean? Is there any way around it?
I've tried googling for answers but there doesn't seem to be much info on this error.

Active directory migration with powershell

I need to migrate from AD Windows2003Forest to AD 2016. I have below script to create users in bulk. My requirement is to map the same SID of older AD to new AD. For example in older AD SID='xyz' then it should be the same in newAD too as SID='xyz'
I am having all the users data along with SID in CSV format & am using below PowerShell script which is somehow not working. As of advice or suggestions.
powershell code snippent:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Department = $User.department
$OU = $User.ou
$sid = $User.sid
$UserPrincipalName = $User.UserPrincipalName
$DistinguishedName = $User.DistinguishedName
#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 $UserPrincipalName `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Department $Department `
-DistinguishedName $DistinguishedName `
-SID $sid `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
You won't be able to assign a SID as that's generated by the domain controller based on a RID. If trying to migrate to a new forest then you'll need to perform a proper AD migration. The old SIDs will be copied onto the migrated users' SID history attributes to allow permissions based on the old SID to still work.
If you simply want to upgrade to a newer version of AD then you're better off joining a newer domain controller to your existing Active Directory forest / domain. The forest functional level mush be 2003 or higher.
As a side note, I'd recommend then getting rid of the 2003 servers as soon as possible as these are no longer supported by Microsoft.

PowerShell New-ADUser : Cannot bind parameter because parameter 'OtherAttributes' is specified more than once

I'm trying to automate AD user creation with PowerShell.
This is the code:
Create AD User
New-ADUser -Name $DisplayName `
-SamAccountName $SamAccountName `
-GivenName $FirstName `
-Surname $LastName `
-DisplayName $DisplayName `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $true `
-PasswordNeverExpires $False `
-ChangePasswordAtLogon $True `
-UserPrincipalName $UserPrincipalName `
-EmailAddress $PrimaryEmailAddress `
-OtherAttributes #{'proxyAddresses' = $proxyAddressesEmailMandatory} `
-OtherAttributes #{'ipPhone' = $UserExtension} `
Attribute "proxyAddress" is necessary so we can have Azure AD Sync between on-premise AD and Azure AD.
But now, we are trying to connect FreePBX with on-premise AD. In order to achieve that, we need to have "ipPhone" attribute.
Before I added last line, script was working fine.
I can see where the problem is, but I don't know how to fix it. Help with an example would be appreciated.
New-ADUser -Name $DisplayName `
-SamAccountName $SamAccountName `
-GivenName $FirstName `
-Surname $LastName `
-DisplayName $DisplayName `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $true `
-PasswordNeverExpires $False `
-ChangePasswordAtLogon $True `
-UserPrincipalName $UserPrincipalName `
-EmailAddress $PrimaryEmailAddress `
-OtherAttributes #{
'proxyAddresses' = $proxyAddressesEmailMandatory
'ipPhone' = $UserExtension
}

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
}