希望有人可以提供帮助,不幸的是,我不是 Powershell 专家
这就是我要的:
根据用户名的第一个字母,在特定 OU 中查找 AD 中的用户。验证他们是否是 AD 组的成员,如果不是;删除用户的一些特定配置文件并将用户添加到该特定组。
我尝试过的部分代码:
Import-Module ActiveDirectory
# OUs needed to be searched for users
$OU1 = 'name of first OU'
$OU2 = 'name of 2nd OU'
$OU3 = 'name of 3rd OU'
# AD group where users needs to be added
$Group = 'name of group'
# Ask for 1st letter of username
$usernameletter = Read-Host -Prompt 'First letter(s) username'
# Create an array with corresponding users
$userslist= @()
$users1 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU1 | select -ExpandProperty samAccountName
$users2 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU2 | select -ExpandProperty samAccountName
$users3 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU3 | select -ExpandProperty samAccountName
$userslist += $users1,$users2,$users3
# check membership of group
$members = Get-ADGroupMember -Identity $Group -Recursive | Select -ExpandProperty sAMAccountName
# Delete userpref files of user when user is not member of the -name of group-
foreach ($user in $userslist)
{
If ($members -contains $user)
{
Write-host "$user exists in group, so userpref files won't be deleted"
}
Else
{
#if users doesn't exist in AD Group - delete userpref files of user
Write-host "$user doesn't exist in group, deleting userpref files of user"
Remove-Item -Path E:\users\$user\pwrmenu\UserPref\{F5BE2CE1-BF67-44E2-B5B3-5E081344A70E}* -Force
}
}
# check if user is part of the group. if not, add it to the group
foreach ($user in $userslist)
{
If ($members -contains $user)
{
Write-host "$user exists in group, so user won't be added to group $group"
}
Else
{
#if users doesn't exist in AD Group - add them to AD Group
Write-host "$user doesn't exist in group, adding user to group $group"
Add-ADGroupMember $Group -Members $userslist
}
}
#end of script
由于某种原因,$userslist 数组已填充,但 $userslist 中的 foreach 循环 $user 不起作用,$user 未填充,并且出现类似错误
删除项目:找不到路径“E:\users\pwrmenu\UserPref”,因为它不存在。Add-ADGroupMember:无法验证参数“成员”的参数。参数为 null、空或参数集合的元素包含 null 值。
希望有人能帮助我!谢谢!
编辑 @Andrew Ryan Davis,
抱歉,对这个网站还不是很熟悉
$userslist 的内容:
PS C:\Users\serverw> $userslist
WGoossensTest
wgoossenstest2
$members 的内容:
PS C:\Users\serverw> $members
用户名1
用户名2
用户名3
ETC