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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.