Create a user on premise based on firstname and lastname - powershell

I am in a hybrid environment and I would like to create a user from exchange using a script.
Goals:
Create an account (Last name + first character of first name). If an account exists, add a number at the end. For example, King, John (Samaccountname should be KingJ1.. if exists, KingJ2...)
The UPN must be the first name.last name... If the last name already exists add a number to the last name. For example, King, John (UPN should be john.king1#contoso, if exists john.king2#contoso.com...)
If anyone can help me it would be really appreciated so that I can save some time. Thanks in advance
Connect-ExchangeOnline
$UserCredential = Get-Credential
$SessionEX2016 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri .../PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $SessionEX2016 -DisableNameChecking
$FirstName = Read-Host "Please enter the Firstname"
$LastName = Read-Host "Please enter the Lastname"
$NewUserLoginID = Read-Host "Please enter a new Login ID" #if the samaccountname exists add a digit
$Manager = Read-Host "Please enter the Login ID of the manager"
$Name = "$($LastName), $($FirstName)"
$DisplayName = $Name
$UPN = "$($FirstName).$($LastName)#contoso.com" #if the upn exists, add a digit to the last name
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"
$OU = "OU=Users,OU=Accounts,DC=com,DC=contoso" # it will creates the user in this OU by default and will move the user to OU where the manager is.
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $NewUserLoginID})
{
#If user does exist, add a digit to samccountname and upn."
}
else
{
#Create User On-Premise
New-RemoteMailbox -Name $Name -FirstName $FirstName -LastName $LastName -SamAccountName $NewUserLoginID -OnPremisesOrganizationalUnit $OU -UserPrincipalName $UPN -Password (ConvertTo-SecureString -AsPlainText $PW -Force) -ResetPasswordOnNextLogon:$true -Archive
$ManagerOU = ((Get-ADUser -Identity $Manager).DistinguishedName -split '(?<!\\),', 2)[-1]
# next, get the user object of the user you want to move
$NewUser = Get-ADUser -Identity $NewUserLoginID
# now move NewUser to the OU where Manager is in
$NewUser | Move-ADObject -TargetPath $ManagerOU
}

You can add while loops to check if a name already exists or not and if so, append a sequence counter to it.
I would also use Splatting for the New-RemoteMailbox cmdlet to make the code more readable (no need for those very long lines of code)
Something like this:
Connect-ExchangeOnline
$UserCredential = Get-Credential
$SessionEX2016 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri .../PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $SessionEX2016 -DisableNameChecking
$OU = "OU=Users,OU=Accounts,DC=com,DC=contoso"
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"
$FirstName = Read-Host "Please enter the Firstname for the new user"
$LastName = Read-Host "Please enter the Lastname for the new user"
$AccountName = $LastName + $FirstName[0] # Last name + first character of first name
# test if a user with that accountname already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "SamAccountName -eq '$AccountName'") {
$AccountName = '{0}{1}{2}' -f $LastName, $FirstName[0], $count++
}
$UPN = "$($FirstName).$($LastName)#contoso.com" #if the upn exists, add a digit to the last name
# test if a user with that UserPrincipalName already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "UserPrincipalName -eq '$UPN'") {
$UPN = '{0}.{1}{2}#contoso.com' -f $FirstName, $LastName, $count++
}
# create a Hashtable for splatting parameters
$userParams = #{
Name = "$($LastName), $($FirstName)"
DisplayName = "$($LastName), $($FirstName)"
FirstName = $FirstName
LastName = $LastName
SamAccountName = $AccountName
OnPremisesOrganizationalUnit = $OU
UserPrincipalName = $UPN
Password = $PW | ConvertTo-SecureString -AsPlainText -Force
ResetPasswordOnNextLogon = $true
Archive = $true
}
# Create User On-Premise and move to the managers OU if possible
try {
New-RemoteMailbox #userParams -ErrorAction Stop
# now check if we can get a managers OU
$Manager = Read-Host "Please enter the Login ID of the manager"
$adManager = Get-ADUser -Filter "SamAccountName -eq '$Manager'"
if ($adManager) {
$ManagerOU = ($adManager.DistinguishedName -split '(?<!\\),', 2)[-1]
# next, get the user object of the new user and move it to the managers OU
Get-ADUser -Identity $AccountName | Move-ADObject -TargetPath $ManagerOU
}
else {
Write-Error "Could not find a manager with SamAccountName '$Manager'"
}
}
catch {
Write-Error $_.Exception.Message
}

Related

How to create samaccountname with maximum 12 character?

I need to create users with max 12 characters.
The last name can contain the first 11 characters (max) + the first letter of the first name
I'm not sure what to add next to $LastName
Can you help me with this?
$OU = "OU=Users,DC=domain,DC=com"
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"
$FirstName = Read-Host "Please enter the Firstname for the new user"
$LastName = Read-Host "Please enter the Lastname for the new user"
$AccountName = $LastName + $FirstName[0] # Last name (11 caracter max) + first character of first name
# test if a user with that accountname already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "SamAccountName -eq '$AccountName'") {
$AccountName = '{0}{1}{2}' -f $LastName, $FirstName[0], $count++
}
$UPN = "$($FirstName).$($LastName)#domain.com" #if the upn exists, add a digit to the last name
# test if a user with that UserPrincipalName already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "UserPrincipalName -eq '$UPN'") {
$UPN = '{0}.{1}{2}#domain.com' -f $FirstName, $LastName, $count++
}
# create a Hashtable for splatting parameters
$userParams = #{
Name = "$($LastName), $($FirstName)"
DisplayName = "$($LastName), $($FirstName)"
FirstName = $FirstName
LastName = $LastName
SamAccountName = $AccountName
OnPremisesOrganizationalUnit = $OU
UserPrincipalName = $UPN
Password = $PW | ConvertTo-SecureString -AsPlainText -Force
ResetPasswordOnNextLogon = $true
Archive = $true
}
# Create User On-Premise and move to the managers OU if possible
try {
New-RemoteMailbox #userParams -ErrorAction Stop
}
catch {
Write-Error $_.Exception.Message
}

If AD account exists, append a counter to the username started at 2

The following script is adding accounts to the Active Directory. In case the username already exists, I want to append a number to the username and try again.
i.e. if cs15csa already exists, it should try again with cs1csa2. If cs1csa2 exists, it should then try with cs1csa3 and so on and so forth.
How do I do that?
# Enter a path to your import CSV file
$ADUsers = Import-csv export.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
# 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 ($Firstname $Lastname) already exists in the 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#iit.uni-ruse.bg" `
-Email "$Username#iit.uni-ruse.bg" `
-ProfilePath '\\leo\%USERNAME%\Profile' `
-Name "$Username" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
You can simply use a loop to test the SamAccountName and inside keep adding a counter number to it until you have found a unique name.
To avoid having to use those nasty backticks on the New-ADUser cmdlet, I would advise to use Splatting
Also, '\\leo\%USERNAME%\Profile' should be "\\leo\$Username\Profile"
Try
# Enter a path to your import CSV file
$ADUsers = Import-Csv export.csv
foreach ($User in $ADUsers) {
$Username = $User.username
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
$count = 2
while (Get-ADUser -Filter "SamAccountName -eq '$Username'") {
$Username = '{0}{1}' -f $User.username, $count++
}
# create the new user using a Splatting Hashtable
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#iit.uni-ruse.bg"
EmailAddress = "$Username#iit.uni-ruse.bg"
ProfilePath = "\\leo\$Username\Profile"
Name = $Username
GivenName = $User.firstname
Surname = $User.lastname
Enabled = $true
DisplayName = '{0} {1}' -f $User.firstname, $User.lastname
Path = $User.ou
AccountPassword = $User.password | ConvertTo-SecureString -AsPlainText -Force
}
# create the user
New-ADUser #userParams
}
An alternative to the while loop above (might be faster, depending on how many similar SamAccountNames there may be in your environment) would be to do this:
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
# first get an array of similar SamAccountNames already present
$similarNames = #((Get-ADUser -Filter "SamAccountName -like '$Username*'").SamAccountName)
$count = 2
while ($similarNames -contains $Username) {
$Username = '{0}{1}' -f $User.username, $count++
}

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'

Ask user to choose option from stored list (AD OU Path)

I modified a PowerShell script to create AD and Office 365 accounts automatically, it works fine but helpdesk need to manually type out the OU path.
Is there a way to pre-define OU path & assign number to it so if the helpdesk press 1 it chooses the OU path assigned to number 1 and so on?
Name DistinguishedName
---- -----------------
Departments OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Operational OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Normal OU=Normal,OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTE..
Sales OU=Sales,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Finance OU=Finance,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
IT OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Application OU=Application,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Infrastructure OU=Infrastructure,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTES..
Marketing OU=Marketing,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
NewBusiness OU=NewBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
ExisitingBusiness OU=ExisitingBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Underwritter OU=Underwritter,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
#Import needed module.
Import-Module ActiveDirectory
#Prompt for needed information to use as variables below
$fullname = Read-Host "Enter Full Name"
$first = Read-Host "First name"
$last = Read-Host "Last name"
$user = Read-Host "Username"
$title = Read-Host "Title"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name
$department = Read-Host "Enter department from above list"
$manager = Read-Host "Manager userame"
$srcuser = Read-Host "Username to copy"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name, DistinguishedName |
Format-Table -Auto
$OU = Read-Host "Select OU from above list"
#Create a new user with the provided information and some static information
New-ADUser -Name "$fullname" -GivenName "$first" -Surname "$last" -DisplayName "$first $last" -Description "$title" -EmailAddress "$first.$last#bnztest.com" -SamAccountName "$user" -UserPrincipalName "$user#bnztest.com" -Manager "$manager" -Title "$title" -AccountPassword (Read-Host -AsSecureString "Please enter the desired password") -Enabled $true -Path $OU
#Add multiple ProxyAddresses if needed
Set-ADUser "$user" -Add #{ProxyAddresses="smtp:$first.$last#bnztest.com"}
#Copy group membership of the source user above
Get-ADUser -Identity "$srcuser" -Properties memberof |
Select-Object -ExpandProperty memberof |
Add-ADGroupMember -Members "$user" -PassThru |
Select-Object -Property SamAccountName >$null
Write-Host 'CHECK AD REPLICATION BEFORE CONTINUING!'
pause
#Sync user to Office 365 using Dir Sync on a remote server
Import-Module ADSync
Start-ADSyncSyncCycle -PolicyType Initial
Start-Sleep -s 100
#License user in Office 365
$AdminName = "admin#testbnz.onmicrosoft.com"
$Pass = Get-Content "C:\Users\Administrator\Desktop\CreateUser\Cred.txt" |
ConvertTo-SecureString
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Pass
Import-Module MSOnline
Connect-MsolService -Credential $cred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Start-Sleep -s 15
Set-MsolUser -UserPrincipalName "$user#bnztest.com" -UsageLocation 'US'
Set-MsolUserLicense -UserPrincipalName "$user#bnztest.com" -AddLicenses "TESTBNZ:O365_BUSINESS_PREMIUM"
Start-Sleep 90
Write-Host 'ENSURE THERE ARE NO ERRORS AND THAT THE MAILBOX HAS BEEN CREATED BEFORE CONTINUING!'
pause
You could add a simple menu like this:
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",
"Exits the loop."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",
"Allows to add another user."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
do
{
$user = New-Object System.Management.Automation.Host.ChoiceDescription "&User", "User"
$it = New-Object System.Management.Automation.Host.ChoiceDescription "&IT", "IT"
$sales = New-Object System.Management.Automation.Host.ChoiceDescription "&Sales", "Sales"
$OUoptions = [System.Management.Automation.Host.ChoiceDescription[]]($user, $it, $sales)
$OU = $host.ui.PromptForChoice("Which OU", "Which OU", $OUoptions, 0)
switch ($OU)
{
0 {Write-Host "The choise is User."}
1 {Write-Host "IT"}
2 {Write-Host "Sales"}
default {Write-Host "The color could not be determined."}
}
$result = $host.ui.PromptForChoice("Continue?", "Do you want to add another user?", $options, 1)
}
while ($result -eq 1)
You can use Out-GridView -OutputMode Single to present the helpdesk with a GUI to select from an object. eg:
$SearchBase = "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,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
Then you can use the OU with your New-ADUser command:
New-ADUser [...] -OU $OU.DistinguishedName

Updating AD User Object Manager Attribute With Contact DN

I have two forests after a merger. Managers of some people reside in the opposite forest. To get around this we have contacts in each forest for all the users of the opposite forest. I am trying to update the manager attribute for several users based on a csv import where I am matching on the managers email address. My script can match the DN of the managers contact, but for some reason will not add it to the ad userobject manager attribute stating it cannot find the DN of an object that is clearly present.
If I run a simple get-adobject with an ldap filter it returns the DN of a managers contact:
PS C:\temp> Get-ADObject -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))" -SearchBase "OU=station,OU=CONTACTS,DC=workplace,DC=COM" |select distinguishedname
distinguishedname
-----------------
CN=Nick Hill,OU=station,OU=Contacts,DC=workplace,DC=com
However, the script below will error when trying to add this DN to a users manager attribute. What's confusing is the DN it claims it cannot find is clearly present per the command above.
The script below errors with:
set-aduser : Identity info provided in the extended attribute: 'Manager' could not be resolved. Reason: 'Cannot find an object with identity: 'CN=Nick Hill,OU=station,OU=Contacts,DC=workplace,DC=com' under: 'DC=workplace,DC=com'.'.
$users = import-csv test1.csv
FOREACH ($user in $users)
{
$username = $user.UserName
$employeeid = $user.employeeid
$city = $user.city
$country = $user.country
$department = $user.department
$division = $user.division
$office = $user.location
$state = $user.state
$postalcode = $user.postal_code
$manageremail = $user.manageremail
$manager = get-aduser -f "mail -eq '$($manageremail)'"
FUNCTION LocalManager
{
get-aduser -f {mail -eq $username} |set-aduser -Manager $manager
}
FUNCTION RemoteManager
{
$data = $manageremail.split("#")
$name = $data[0]
$namesplit = $name.split(".")
$fname = $namesplit[0]
$lname = $namesplit[1]
$rmanager = Get-ADObject -SearchBase 'OU=station,OU=Contacts,DC=workplace,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"
get-aduser -f {mail -eq $username} |set-aduser -Manager "$rmanager"
}
IF ($manager -eq $null)
{
RemoteManager
}
Else
{
Localmanager
}
}
I have had a similar error on my own script to handle cross-domain user population. I've exported some of our old decom'd user accounts and am importing them (with suitably generic information) to populate our test/dev environments.
Unfortunately when I try and create these accounts as new users in AD with managers in different domains, I find the following problem:
Set-ADUser : The server is unwilling to process the request
At line:1 char:1
+ Set-ADUser -Identity $user.SamAccountName -Manager $user.Manager -Ser ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (user.name:ADUser) [Set-ADUser], > ADInvalidOperationException
+ FullyQualifiedErrorId : > ActiveDirectoryServer:8245,Microsoft.ActiveDirectory.Management.Commands.SetADUser
So this was in an attempt to set the user with the manager's DN.
function create-testaccts {
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,Position=1)]
[string] $rootPath ,
[Parameter(Mandatory=$True,Position=2)]
[string] $userList ,
[Parameter(Mandatory=$True,Position=3)]
[string] $pw ,
[Parameter(Mandatory=$True,Position=4)]
[string] $OU = $(throw "Please specify a query.")
)
$newUsers = import-csv $userList
$password = $pw | ConvertTo-SecureString -AsPlainText -Force
foreach ($user in $newUsers){
$profPath = $rootpath + $user.samaccountname
try {
write-host -fore Cyan "Creating the user profile path - $profPath"
new-item $profPath -ItemType Directory -Force -ErrorAction stop | Out-Null
}# END OF TRY
Catch [System.Management.Automation.ActionPreferenceStopException] {
write-host -fore Yellow "caught a StopExecution Exception - Home directory creation "
$error[0]
}# END OF CATCH
try {
Write-Host -Fore Cyan "Creating the user object in AD -" $user.Name
# Name - Name
# Givenname - Firstname
# Surname - Lastname
# Password - AccountPassword Specific to new-aduser
# SamAccountName - same in both command/attribute name used userlogon and samaccount
# Manager - same in both command/attribute name
# ProfilePath - same in both command/attribute name
# HomeDirectory - same in both command/attribute name
# HomeDrive - same in both command/attribute name
# Enabled - False - same in both command/attribute name
# UserPrincipalName - same in both command/attribute name
# Server
$name = $user.Name
New-ADUser -Name "$name" `
-GivenName $user.givenname `
-Surname $user.surname `
-DisplayName $user.displayname `
-SamAccountName $user.SamAccountName `
-Path $ou `
-AccountPassword $Password `
-ProfilePath $user.profilepath `
-HomeDirectory $user.HomeDirectory `
-HomeDrive $user.homedrive `
-Enabled $False `
-UserPrincipalName $user.UserPrincipalName `
-Server domain.local `
-Credential $creds `
-ErrorAction Stop
#-Manager $user.Manager `
}# END OF TRY
Catch [System.Management.Automation.ActionPreferenceStopException] {
Write-Host -fore Yellow "caught a StopExecution Exception - Account Creation"
$error[0]
}# END OF CATCH
}#END FOREACH NEW USERS
} #END OF FUNCTION (CREATE-TESTACCTS)
When I try and use this with a trusted domain it fails due to the manager DN not being found in the local domain. I've tried multiple ways, but can't seem to find out why it does this and won't seem to chain.
However i found a workaround where i can create the user without the mgr field and then set the user using the following link/command:
https://social.technet.microsoft.com/Forums/office/en-US/ade19ad5-ecfd-48af-987b-5958983676b6/active-directory-update-the-manager-field-when-the-manager-is-in-a-different-domain?forum=ITCG
Set-ADUser -Identity $ADUser_Domain1 -Credential $DomainAdmin_Domain1 -Server $Domain1 -Replace #{manager = $ManagerDN_Domain2}
This works and I have no idea why the replace works, but seems to require the credential being passed. I've even tried with passing the domain 2 credential.
Overall this is very confusing and i feel like if the local session credential has rights between domains it should be able to look this up without issue. Any additional help or explanation would be REALLY helpful!