I want to add a random generated password to my newly created Active Directory User - powershell

I want to add a randomly generated password to my newly created Active Directory User. I have written a function to generate the password. I am using Powershell V2.0
I tried the below but did not help.
Import-Module ActiveDirectory
[xml]$dataSource = Get-Content C:\Names1.xml
$name = Read-Host 'Please enter the table name : '
$user_logon = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (user logon)'}
$display_name = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (display name)'}
$pre_windows = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (pre-Windows 2000)'}
Function GET-Temppassword() {
Param(
[int]$length=10,
[string[]]$sourcedata
)
For ($loop=1; $loop –le $length; $loop++) {
$TempPassword+=($sourcedata | GET-RANDOM)
}
return $TempPassword
}
switch ($name)
{
DevTable{foreach($dataRecord in $dataSource)
{
try
{
$cn=$user_logon.Output_Value
$sAMAccountName=$user_logon.Output_Value
$givenName=$user_logon.Output_Value
$sn=$user_logon.Output_Value
$displayName=$display_name.Output_Value
$userPrincipalName=$sAMAccountName + “#test.com”;
$alphabet=$NULL;For ($a=65;$a –le 90;$a++) {$alphabet+=,[char][byte]$a }
$TempPassword1 = GET-Temppassword –length 10 –sourcedata $alphabet
New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName -Surname $sn -DisplayName $displayName -UserPrincipalName $userPrincipalName -AccountPassword $TempPassword1 -PasswordNeverExpires $true -Path "OU=Service,OU=Accounts,DC=xyz,DC=com"
set-aduser $cn -replace #{comment="xxyyzz"}
set-aduser $cn -replace #{"account"=1}
Add-ADGroupMember -Identity xyz -Member $cn
Add-ADGroupMember -Identity "Service Accounts" -Member $cn
write-host "New DevTable ADUser has been created!!!";
}
catch [Exception]
{
write-host "Error - Requested AD Service Account is already present...Please check & confirm " -foreground "red"
}
}
break;
}
default {"The table could not be determined!!!"}
}
[System.GC]::Collect()
Please have a look.Thanks.

This is written so that $sourceData can be a string like the following. If you really want to pass $sourcedata as an array of char remove the [char[]] cast from the function.
$sourcedata="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-$"
Function GET-Temppassword() {
Param(
[int]$length=10,
[string[]]$sourcedata
)
-join ([char[]] $sourcedata | GET-RANDOM -count $length)
}
get-temppassword $sourceData 20
GVTXxF13ibnBK5AQOu-P

Related

Powershell script to automate create Ad User and group member

Iam begineer to powershell, trying to create a AD User and a group member, here the query is groups should be array (multiple groups)it shouldn't be one to one mapping using for loop, try and catch method need to check all the scenarioes like user already exists on AD as well as Group if not exists add New-ADUser and group Add-ADGroupMember
the code which i was trying but somewhere the logic missed or my script is not correct, its not going inside foreach ($grp in $Group)
Param
(
[parameter(Mandatory=$true)]
[string] $fname,
[parameter(Mandatory=$true)]
[string] $lname,
[parameter(Mandatory=$true)]
[string] $upn,
[parameter(Mandatory=$true)]
[string] $desc,
[parameter(Mandatory=$true)]
[string] $Email,
[parameter(Mandatory=$true)]
[string[]] $Group
)
# Define UPN
$SamAccount = "$fname.$lname"
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$SamAccount'" | Select-Object SamAccountName
#$ADGroups = Get-ADGroup -Filter * | Select-Object Name
#Generate a Randam Secure Password to a User
Function GenerateStrongPassword ([Parameter(Mandatory=$true)][int]$PasswordLenght)
{
Add-Type -AssemblyName System.Web
$PassComplexCheck = $false
do {
$newPassword=[System.Web.Security.Membership]::GeneratePassword($PasswordLenght,1)
If ( ($newPassword -cmatch "[A-Z\p{Lu}\s]") `
-and ($newPassword -cmatch "[a-z\p{Ll}\s]") `
-and ($newPassword -match "[\d]") `
-and ($newPassword -match "[^\w]")
)
{
$PassComplexCheck=$True
}
} While ($PassComplexCheck -eq $false)
return $newPassword
}
$password = GenerateStrongPassword (10)
#Adding New User to AD and to the Groups
if ($ADUser -eq $null){
New-ADUser -GivenName "$fname" -Surname "$lname" -Initials $initials -displayName "${fname} ${lname}" -UserPrincipalName $upn -Description "$desc" -Name "$fname $lname" -EmailAddress "$email" -SamAccountName $SamAccount -ChangePasswordAtLogon $true -AccountPassword $(ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $false -Path "OU=aws,DC=azure,DC=com" -Server "Domain"
"ResponseMessage: successfull- User " +$UPN+ " added to the AD and user's password is " +$password
foreach ($grp in $Group)
{
$grp = $grp.tostring()
$ADGroups = Get-ADGroupMember -Identity $grp| Select-Object name
if($ADGroups -eq $null){
Add-ADGroupMember -Identity $grp -Members $ADUser
"ResponseMessage: successfull- User " +$UPN+ " added to the $grp"
}
}
}
#if Ad user already exists but not exist on Group
elseif($ADUser){
"ResponseMessage: successfull- User " +$UPN+ " is already exists to the AD"
foreach ($grp in $Group)
{
$grp = $grp.tostring()
$ADGroups = Get-ADGroupMember -Identity $grp| Select-Object name
if($ADGroups -eq $null){
Add-ADGroupMember -Identity $grp -Members $ADUser
"ResponseMessage: successfull- User " +$UPN+ " added to the $grp"
}
else{
"User is " +$UPN+ " is already exists on the $grp"
}
}
}
else{
"user is not valid"
}
One of the main issues is you're attempting to add $ADUser to $grp while it's null. You have if ($ADUser -eq $null){..} which will only run if $ADUser is null, then you're attempting to use Add-ADGroupMember -Identity $grp -Members $ADUser where it will not work. Your immediate fix is to assign the newly created user account to $ADUser; $ADUser = New-ADUser.
The next issue would be the way you're comparing to see if the user is already part of the group via Get-ADGroupMember -Identity $grp which will not tell you that, besides getting the group members of the specified group. You can fix this by querying for the memberof property and comparing your $grp to the returned user groups; $grp also doesn't need to be converted to a string (.ToString()) seeing as it's already a string via your [string[]] $Groups explicit cast type.
Fixing the above, you end up with this:
Param
(
[parameter(Mandatory=$true)]
[string] $fname,
[parameter(Mandatory=$true)]
[string] $lname,
[parameter(Mandatory=$true)]
[string] $upn,
[parameter(Mandatory=$true)]
[string] $desc,
[parameter(Mandatory=$true)]
[string] $Email,
[parameter(Mandatory=$true)]
[string[]] $Group
)
# Define UPN
$SamAccount = "$fname.$lname"
$ADUser = try { Get-ADUser -Identity $SamAccount -Properties 'memberof' } catch { }
#Adding New User to AD and to the Groups
if ($null -eq $ADUser) {
$newUserParams = #{
GivenName = $fname
Surname = $lname
Initials = $initials
DisplayName = "$fname $lname"
UserPrincipalName = $upn
Description = $desc
Name = "$fname $lname"
EmailAddress = $Email
SamAccountName = $SamAccount
ChangePasswordAtLogon = $true
AccountPassword = ConvertTo-SecureString $password -AsPlainText -Force
Enabled = $false
Path = "OU=aws,DC=azure,DC=com"
Server = "Domain"
PassThru = $true
}
$ADUser = New-ADUser #newUserParams
"ResponseMessage: successfull- User $UPN added to the AD and user's password is $password"
foreach ($grp in $Group)
{
$ADGroups = try { Get-ADGroup -Identity $grp } catch { }
if ($ADGroups) {
Add-ADGroupMember -Identity $grp -Members $ADUser.SAMAccountName
"ResponseMessage: successfull- User " + $UPN + " added to the $grp"
}
}
}
elseif ($ADUser) {
"ResponseMessage: successfull- User " + $UPN + " is already exists to the AD"
$userGroups = $ADUser.MemberOf.Foreach{ ($_ -Split 'CN=|,OU')[1] }
foreach ($grp in $Group)
{
if ($grp -notin $userGroups) {
Add-ADGroupMember -Identity $grp -Members $ADUser.SAMAccountName
"ResponseMessage: successfull- User $UPN added to the $grp"
}
else {
"User $UPN already exists in $grp"
}
}
}
else {
"user is not valid"
}
I removed the function GenerateStrongPassword for brevity; just re-add it.

AD-user script has no output

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

ADuser not adding samAccountName after changing Variable

Thanks in advance !
I have made a script and in this script, I add users from excel to AD and it works for 99% but I need to make 1 change to it but when I do that it gives me errors.
Import-Csv -Path C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv |foreach{
#All strings of variables you need out of excel
$Firstname = $_.Firstname
$Lastname = $_."Last Name"
$Displayname = $_."Display Name"
$Extraname = $_."Display Name"
$Logonname = $_."Logon Name"
$Accountpassword = $_.AccountPassword
$Description = $_.Description
$Jobtitle = $_."Job Title"
$Department = $_.Department
$Company = $_.Company
$Telephonenumber = $_.TelephoneNumber
$Mobilenumber = $_."Mobile number"
$Street = $_.Street
$PObox = $_."P.O. Box"
$City = $_.City
$State = $_."State / Province"
$Zip = $_.Zip
$Country = $_.Country
$Manager = $_.Manager
$ProxyEmail = $_."Proxy Address + Email(SMTP)"
$ProxyAdress = $_."Proxy Addresss(smpt)"
$ProxySip = $_."Proxy address (SIP)"
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last name".ToLower()))
#int
$i = 1
$u = 1
$o = 1
#Check if its over 18 chars if it is it will be shortened
if ($Displayname.Length -gt 18) { $Displayname = $Displayname.Substring(0,18) }
if ($Extraname.Length -gt 18) { $Extraname = $Extraname.Substring(0,18) }
try
{
while (Get-ADUser -F {SamAccountName -eq $Extraname})
{
Write-Warning "Er bestaat al een account met de naam $Extraname"
$Extraname = $Displayname + [string]$i
$i++
$Logonname = $Logonname + [string]$o
$o++
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last Name".ToLower()))
$Final = $Final + [string]$u
$u++
}
}
catch{}
finally
{
$Logonname = $Logonname -replace ' ',''
$Final = $Final -replace ' ',''
echo $Final
New-ADUser -Path "ou=Users,ou=NLHKH,dc=CONTOSO,dc=com" `
-SamAccountName $Extraname `
-GivenName $Firstname `
-Name $Extraname `
-Surname $Lastname `
-DisplayName $Extraname `
-UserPrincipalName $Final `
-accountpassword(ConvertTo-SecureString "Password1" -AsPlainText -force) `
-ChangePasswordAtLogon $true `
-Description $Description `
-Title $Jobtitle `
-Department $Department `
-Company $Company `
-MobilePhone $Mobilenumber `
-StreetAddress $Street `
-City $City `
-State $State `
-PostalCode $Zip `
-POBOX $PObox
}
}
As you can see it should work like this but I need to change -SamAccountName to $final or at least to the same Variable as $Final. But that won't do.
Personally, I would change quite a lot of your script.
First of all, you need two loops to figure out if
you get a valid unique SamAccountName
you get a valid unique UserPrincipalName
The ProxyAddresses need extra care aswell. You need to create an array of the 3 Proxy* fields in the CSV and add that with parameter OtherAttributes.
Mind that his will not accept a 'normal' array and that it needs to be cast with [string[]] to form a strongly typed string array.
Finally, use Splatting for the New-ADUser cmdlet to get rid of those nasty backticks.
Something like this:
Import-Csv -Path 'C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv' | ForEach-Object {
# unused fields in the CSV:
# $Logonname = $_."Logon Name"
# $Country = $_.Country
# $Manager = $_.Manager
# construct a SamAccountName from the DisplayName in the CSV
# replace all invalid characters and cut off anything over 20 characters
$SamAccountName = $_."Display Name" -replace '[\x00-\x20"[\]:;|=+*?<>/,#\s]'
if ($SamAccountName.Length -gt 20) { $SamAccountName = $SamAccountName.Substring(0, 20) }
$temp = $SamAccountName
# enter an endless loop to test if that user with that SamAccountName already exists
$i = 1
while ($true) {
$user = Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue
# if a user with that SamAccountName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new SamAccountName to test
while (($temp + $i).Length -gt 20) {
$temp = $temp.Substring(0, $temp.Length - 1)
}
$SamAccountName = '{0}{1}' -f $temp, $i
$i++
}
# since your UPN uses a different format than 'SamAccountName#CONTOSO.com',
# start another loop to make sure that too is unique
# CHANGE #CONTOSO.com TO THE REAL DOMAIN NAME
$UserPrincipalName = '{0}.{1}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower()
$i = 1
while ($true) {
$user = Get-ADUser -Filter "UserPrincipalName -eq '$UserPrincipalName'" -ErrorAction SilentlyContinue
# if a user with that UserPrincipalName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new UserPrincipalName by adding a sequence number to test
$UserPrincipalName = '{0}.{1}{2}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower(), $i
$i++
}
# next, create an array of the Proxy Addresses. Watch the spelling in the CSV headers!
$ProxyAddresses = ('SMTP:{0}' -f ($_."Proxy Address + Email(SMTP)" -replace '^SMTP:')),
('smtp:{0}' -f ($_."Proxy Address(smpt)" -replace '^smtp:')),
('SIP:{0}' -f ($_."Proxy address (SIP)" -replace '^SIP:'))
# now that we have unique names and a ProxyAddresses array, we can create the user
$NewUserParms = #{
'SamAccountName' = $SamAccountName
'Name' = ('{0} {1}' -f $_.FirstName, $_."Last Name").Trim()
'DisplayName' = $_."Display Name"
'UserPrincipalName' = $UserPrincipalName
'GivenName' = $_.FirstName
'Surname' = $_."Last Name"
'Description' = $_.Description
'Title' = $_."Job Title"
'Department' = $_.Department
'Company' = $_.Company
'AccountPassword' = ConvertTo-SecureString $_.AccountPassword -AsPlainText -Force
'ChangePasswordAtLogon' = $true
'Enabled' = $true
'OfficePhone' = $_.TelephoneNumber
'MobilePhone' = $_."Mobile number"
'StreetAddress' = $_.Street
'City' = $_.City
'State' = $_."State / Province"
'PostalCode' = $_.Zip
'POBox' = $_."P.O. Box"
'EmailAddress' = $_."Proxy Address + Email(SMTP)" -replace '^SMTP:'
'Path' = "OU=Users,OU=NLHKH,DC=CONTOSO,DC=com"
# ProxyAddresses needs cast to [string[]]
'OtherAttributes' = #{'proxyAddresses' = [string[]]$ProxyAddresses}
# add other properties to set from the CSV here if needed.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}

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!

how to add users into a specific group in active directory based on the user selection type powershell

I am working a script to add user to a specific group at the moment user gets created as a normal domain user but i am not sure how to add a user to an admin group of tester group.Also how to check if user doesnot enter first name i should prompt user to enter first name I am using the following script
$NewUser = Read-Host "New Username"
$firstname = Read-Host "First Name"
$Lastname = Read-Host "Last Name"
$NewName = "$firstname $lastname"
New-ADUser -SamAccountName $NewUser -Name $NewName -GivenName $firstname -Surname
$lastname -displayname $Newname -UserPrincipalName $firstname#handmade.local -Path
"CN=Users,DC=mydomain,DC=local" -AccountPassword (ConvertTo-SecureString -AsPlainText
"Password" -Force) -Enabled $true
write-host "!!!New User"$NewUser "Created!!!"
I am getting the following error:
when I run this script
New-ADUser -SamAccountName $NewUser -Name $NewName -GivenName $FirstName -Surname
$LastName -displayname $NewName -UserPrincipalName $FirstName#mydomain.local -Path
"CN=Users,DC=mydomain,DC=local" -AccountPassword (ConvertTo-SecureString -AsPlainText
"password" -Force) -Enabled $true
$h = #{1="Dev";2="Admins"}
Write-Host "Please select:"
$h.getEnumerator() |sort | % {
Write-Host ([string]$_.Name +". " + $_.Value)
}
Write-Host
[string]$g = Read-Host -Prompt "Select group number or numbers, coma separated"
$groups = $g -split ","
foreach($group in $groups){
Add-ADGroupMember -Identity $h[$group] -Members $NewUser
}
write-host "!!!New User"$NewUser "Created!!!"
exit 0
}
}
Error:
Add-ADGroupMember : Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument
and try the command again.
At C:\Users\Administrator\Desktop\add user to AD.ps1:60 char:33
+ Add-ADGroupMember -Identity $h[$group] -Members $NewUser
I am selecting the groups as 1,2
Try this - groups and their corresponding number choice mappings are defined in $h. When prompted enter coma separated values ie. 1 or 2,3
$h = #{1="group1";2="group2";3="group"}
Write-Host "Please select:"
$h.getEnumerator() |sort | % {
Write-Host ([string]$_.Name +". " + $_.Value)
}
Write-Host
[string]$g = Read-Host -Prompt "Select group number or numbers, coma separated"
$groups = $g -split ","
foreach($group in $groups){
$group_to_add = [string]($h[$group])
Write-Host "Adding $NewUser to $group_to_add"
Add-ADGroupMember -Identity $group_to_add -Members $NewUser
}
This has done the job for me.
$h = #{1="Dev";2="Admins"}
Write-Host "Please select:"
$h.getEnumerator() |sort | % {
Write-Host ([string]$_.Name +". " + $_.Value)
}
Write-Host
[string] $g = Read-Host -Prompt "Select group number or numbers, coma separated"
$groups = $g -split ","
foreach($group in $groups){
[int32] $no = $group
Add-ADGroupMember -Identity $h.item($no) -Members $NewUser
}