在創建帳戶后,我正在嘗試將用戶從入職 CSV 檔案移動到幾個不同的 OU,但我遇到了語法問題。office是否可以在用戶 Active Directory屬性上對某個關鍵字(例如“遠程”)使用通配符查找?下面是代碼片段。任何幫助,將不勝感激。
$map = @{
'China' = "China OU DistinguishedName"
'Russia' = "Russia OU DistinguishedName"
'US - Miami' = "Miami OU DistinguishedName"
'US - Tampa' = "Tampa OU DistinguishedName"
'US - Reno' = "Reno OU DistinguishedName"
'US - Charleston' = "Charleston OU DistinguishedName"
}
foreach($line in Import-Csv "C:\Test\Test Files\AD_Test.csv") {
$firstname = $line.'Legal First Name'.Trim()
$preferred_firstname = $line.'Preferred First Name'.Trim()
if($preferred_firstname){
$firstname = $preferred_firstname
}
$lastname = $line.'Last Name'.Trim()
$displayname = $firstname " " $lastname
$param = @{
# create a filter for this user
# try to find him either by CommonName OR SamAccountName OR DisplayName
LDAPFilter = "(|(cn=$displayName)(samAccountName=$displayName)(displayName=$displayName))"
Properties = "Office"
}
# if the user can be found in AD
if($user = Get-ADUser @param) {
# if the user's Office cannot be found in `$map`
if(-not $map.ContainsKey($user.Office)) {
Write-Warning "Office for '$displayName' could not be determined, skipping."
# go to next line in Csv
continue
}
# if the user's Office can be found in `$map`, move it to the destination OU
$user | Move-ADObject -TargetPath $map[$user.Office]
# and after moving it, skip below logic, go next
continue
}
# if the user could not be found in AD
Write-Warning "'$displayName' could not be found in AD."
}
uj5u.com熱心網友回復:
如上一個答案中所述,哈希表應該用于精確查找,但是您仍然可以使用它,但是您需要添加更多條件以防Office在$map. 為此,您可以使用 aswitch來評估多個條件。
要了解:outer標簽的使用,請參閱about_Continue。
$map = @{
# stays as-is, only exact values here
}
# set `outer` label for this loop
:outer foreach($line in Import-Csv "C:\AD_Test.csv") {
# `$displayname` and `$param` code stays as-is here
# if the user could not be found in AD
if(-not ($user = Get-ADUser @param)) {
# display the warning
Write-Warning "'$displayName' could not be found in AD."
# and skip next logic
continue
}
# if the user can be found in AD, switch on `$user.Office`
$destination = switch($user.Office) {
# if the value is found on `$map` hashtable
# get the destination OU, and break the switch loop
{ $map.ContainsKey($_) } { $map[$_]; break }
# if the value contains "Remote", output this OU and break the loop
{ $_ -like "*Remote*" } { 'OU=Remote Here,DC=DOMAIN,DC=com'; break }
# if above conditions were `$false`, the Default action is
# display the warning message and go to next line of Csv
Default {
Write-Warning "Office for '$displayName' could not be determined, skipping."
continue outer
}
}
# if we are here, we can assume `$destination` is populated
# hence we can move the user
$user | Move-ADObject -TargetPath $destination -WhatIf
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487118.html
