> # Start transcript Start-Transcript -Path C:\Temp\Add-ADUsers.log -Append
>
> # Import AD Module Import-Module ActiveDirectory
>
> # Import the data from CSV file and assign it to variable $Users = Import-Csv "C:\Temp\jacktest.csv"
>
> # Specify target group where the users will be added to
> # You can add the distinguishedName of the group. For example: CN=Pilot,OU=Groups,OU=Company,DC=exoip,DC=local $Group = "JackTest"
>
> foreach ($User in $Users) {
> # Retrieve UPN
> $UPN = $User.UserPrincipalName
>
> # Retrieve UPN related SamAccountName
> $ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'" | Select-Object SamAccountName
>
> # User from CSV not in AD
> if ($ADUser -eq $null) {
> Write-Host "$UPN does not exist in AD" -ForegroundColor Red
> }
> else {
> # Retrieve AD user group membership
> $ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName | Select-Object Name
>
> # User already member of group
> if ($ExistingGroups.Name -eq $Group) {
> Write-Host "$UPN already exists in $Group" -ForeGroundColor Yellow
> }
> else {
> # Add user to group
> Add-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName -WhatIf
> Write-Host "Added $UPN to $Group" -ForeGroundColor Green
> }
> } } Stop-Transcript
代碼未成功將用戶添加到組我正在嘗試將 900 多個用戶從 CSV 添加到帶有標題“UserPrincipalName”的 AD 組 如果陳述句按預期作業,則報告 else。
uj5u.com熱心網友回復:
我認為您的代碼足夠好,我認為沒有進行更改的原因是-WhatIfswitch ,它應該顯示一條訊息而不是執行操作。
除此之外,您還可以考慮幾件事,一個是| Select-objectthis 會將物件修改為PSCustomObject,您將失去擁有ADObject. 另一件事是您使用的比較,而不是-eq您更好使用的串列-contains,因此您得到 true/false 。第三但并非最不重要的是$null與(-not $ADUser)
考慮到所有這些,我將代碼修改為我的評論。
foreach ($User in $Users) {
# Retrieve UPN
$UPN = $User.UserPrincipalName
# Retrieve UPN related SamAccountName
$ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'"
# User from CSV not in AD
if (-not $ADUser) {
Write-Host "$UPN does not exist in AD" -ForegroundColor Red
}
else {
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName
# User already member of group
if ($ExistingGroups.Name -contains $Group) {
Write-Host "$UPN already exists in $Group" -ForeGroundColor Yellow
}
else {
# Add user to group
Add-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName
Write-Host "Added $UPN to $Group" -ForeGroundColor Green
}
}
} Stop-Transcript
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409798.html
標籤:
