由于我不是专业程序员,我应该使用哪种逻辑来易于理解,但有效的脚本?我正在编写一个搜索所有AD用户并基于AD属性(即办公室)的脚本,它会将一些字符串写入其他几个属性(城市,邮政编码等)。我一直在使用Foreach,然后使用set-ADUser with replace或where子句在该循环中。或者是一堆IF,IfElse语句的非常混乱的方式。另外,我开始查看Switch(Case)语句。
有什么建议吗?
从小处开始,我从这开始:
$Users = Get-ADUser -searchbase "OU=users,OU=testing,DC=blah,DC=company,DC=com" -filter {samaccountname -like "r*"} -properties * | Select samaccountname,streetaddress,l, postalcode,st,physicaldeliveryofficename
foreach ($user in $users) {
set-aduser $user -city "NoWhere" -Postalcode "B2B 2B2"| where {$_.physicaldeliveryofficename -eq "Head Office"}
}
或改为开关:
$Users = Get-ADUser -searchbase "OU=users,OU=testing,DC=blah,DC=company,DC=com" -filter {samaccountname -like "remot*"} -properties * | Select samaccountname,streetaddress,l, postalcode,st,physicaldeliveryofficename
foreach ($user in $users) {switch ($users.physicaldeliveryofficename){
"Nowhere town" { -city "NoWhere" -postalcode "A1A A1A"}
"Anywhereville" { -city "Anywhere" -postalcode "B1B B1B"}
}}
答案 0 :(得分:2)
ForEach
语句使用| ForEach { ......... }
。|
,(
,{
,,
,未完成的双操作数运算符(如+
或在行尾使用一个反引号来包装长参数列表。Switch
是这里的方法,因为在流水线操作时,没有可用的整个列表,因此每个元素都应单独处理。
Get-ADUser -searchbase "OU=users,OU=testing,DC=blah,DC=company,DC=com" `
-filter 'samaccountname -like "r*"' `
-properties * |
Select samaccountname,
streetaddress,
l,
postalcode,
st,
physicaldeliveryofficename |
ForEach {
switch ($_.physicaldeliveryofficename) {
"Nowhere town" { $city = "NoWhere"; $postalcode = "A1A A1A"; break }
"Anywhereville" { $city = "Anywhere"; $postalcode = "B1B B1B"; break }
default { $city = "?"; $postalcode = "" }
}
Set-ADUser $_ -City $city -Postalcode $postalcode
}