我正在尝试创建一个将人员添加到组中的脚本,并且我想要类似IF语句的内容,如果某个员工在某个OU中,它将自动将我们的员工添加到其VLAN组中。假设我们的员工处于OU =测试状态,他们将被添加到“测试VLAN”组中 我想将此添加到我的脚本中,该脚本检查它们所在的OU并将它们添加到特定的VLAN组。
谢谢
答案 0 :(得分:1)
在这里,不需要活动目录模块。
您需要根据自己的喜好调整LDAP过滤器。目前,它对填充了“标题”字段的所有用户对象执行此操作
$VerbosePreference = "Continue"
[void][System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
# LDAP search filter, this gets all users with the title field populated
$searchFilter = "(&(objectclass=user)(title=*))"
# Hash mapping between group name and OU
$mapping = @(
[PSCustomObject]@{ Name = "Test VLAN"; Value = "OU=Test,OU=Users,DC=contoso,DC=com"}
[PSCustomObject]@{ Name = "Test VLAN 2"; Value = "OU=Test2,OU=Users,DC=contoso,DC=com"}
[PSCustomObject]@{ Name = "Test VLAN 123123"; Value = "OU=Test123123,OU=Users,DC=contoso,DC=com"}
)
# Get all users in Active Directory
$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"")
$directorySearcher.Filter = $searchFilter
$directorySearcher.PropertiesToLoad.Add("samaccountname")
$directorySearcher.PropertiesToLoad.Add("distinguishedname")
$users = $directorySearcher.FindAll()
$domainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
$principalContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new("Domain",$domainName)
# Loop through users and add them to group
foreach ($user in $users) {
$userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principalContext, $user.Properties.samaccountname)
if ($userPrincipal) {
$vlanGroup = $mapping.Where({$user.Properties.distinguishedname.EndsWith($_.Value)})
if ($vlanGroup) {
$groupPrincipal = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($principalContext, $vlanGroup.Name)
if ($userPrincipal.IsMemberOf($groupPrincipal)) {
Write-Verbose "User '$($user.Properties.samaccountname)' is already memberof '$($vlanGroup)'"
}
else {
$groupPrincipal.Members.Add($userPrincipal)
$groupPrincipal.Save()
Write-Verbose "Added user '$($user.Properties.samaccountname)' to group '$($vlanGroup)'"
}
}
else {
Write-Verbose "No VLAN mapping found for user '$($user.Properties.samaccountname)'"
}
}
else {
Write-Verbose "Unable to find userprincipal for '$($user.Properties.samaccountname)'"
}
Clear-Variable 'userPrincipal', 'vlanGroup', 'groupPrincipal' -ErrorAction SilentlyContinue
}