因此,我正在尝试使用PowerShell和CSV文件填充用户的街道地址以及城市,州,邮政编码等(如果他们搬到新的办公地点,则他们的街道,城市,州,邮政编码将是适当更新)。显然,我的OU是按位置来组织的。我的CSV文件有5列(街,街2,城市,州,邮政编码)。 Street2通常是我想要在另一行上使用的套件。虽然如果zip开头为零,则它会丢失,但这是另一个主题。
一切正常,直到第9行(Get-ADUser
),然后从第10行开始(Set-ADUser
),它失败了,我想我知道为什么我还没有弄清楚如何克服它。我无法在$_
循环中将for-eachobject
用作两个不同的值
Get-ADUser
和Set-ADUser
。
Import-CSV .\Offices.csv |
ForEach-Object {
if($_.Office -eq "Office1"){
$OUStr = "OU=Office1,OU=User Accounts,DC=domain,DC=local"
}elseif($_.Office -eq "Office2"){
$OUStr = "OU=Office2,OU=User Accounts,DC=domain,DC=local"
}
Get-ADUser -Filter "L -eq `"$($_.Office)`"" -SearchBase "$OUStr" -Properties streetAddress,L,st,postalCode |
Set-ADUser -Replace @{
streetAddress="$_.Street" + "`r`n" + "$_.Street2"
L="$_.City"
st="$_.State"
postalCode="$_.Zip"
}
}
任何建议将不胜感激。
答案 0 :(得分:1)
如果定义一个哈希表来存储所有要更新的属性并将其用于Set-ADUser
cmdlet,则可能会更容易。
使用-替换为LDAP属性名称
$CSV = Import-CSV .\Offices.csv
foreach ($user in $CSV) {
switch ($user.Office) {
"Office1" { $OUStr = "OU=Office1,OU=User Accounts,DC=domain,DC=local"; break }
"Office2" { $OUStr = "OU=Office2,OU=User Accounts,DC=domain,DC=local"; break }
}
# With –Replace you're using the LDAP names of the properties rather than the PowerShell name.
$attribs = @{
streetAddress = "{0}`r`n{1}" -f $user.Street, $user.Street2
l = $user.City
st = $user.State
postalCode = $user.Zip
}
Get-ADUser -Filter "City -eq '$($user.Office)'" -SearchBase $OUStr |
Set-ADUser -Replace $attribs
}
使用PowerShell或GUI属性名称来电镀参数
$CSV = Import-CSV .\Offices.csv
foreach ($user in $CSV) {
switch ($user.Office) {
"Office1" { $OUStr = "OU=Office1,OU=User Accounts,DC=domain,DC=local"; break }
"Office2" { $OUStr = "OU=Office2,OU=User Accounts,DC=domain,DC=local"; break }
}
# With splatting you use the PowerShell or GUI names of the properties.
$attribs = @{
StreetAddress = "{0}`r`n{1}" -f $user.Street, $user.Street2
City = $user.City
State = $user.State
PostalCode = $user.Zip
}
Get-ADUser -Filter "City -eq '$($user.Office)'" -SearchBase $OUStr |
Set-ADUser @attribs
}
希望这会有所帮助
答案 1 :(得分:0)
我认为这会对您有所帮助
Import-CSV .\Offices.csv |
ForEach-Object {
if($_.Office -eq "Office1"){
$OUStr = "OU=Office1,OU=User Accounts,DC=domain,DC=local"
}elseif($_.Office -eq "Office2"){
$OUStr = "OU=Office2,OU=User Accounts,DC=domain,DC=local"
}
$streetAddress = $_.street + "`r`n" + $_.street2
$City = $_.City
$state = $_.State
$postalCode = $_.zip
Get-ADUser -Filter "L -eq `"$($_.Office)`"" -SearchBase "$OUStr" -Properties streetAddress,L,st,postalCode |
Set-ADUser -Replace @{
streetAddress=$streetAddress
L=$City
st=$state
postalCode=$postalCode
}
}
我在Get-Aduser命令之前为替换哈希表中所需的所有内容设置变量。这将允许您引用传递到ForEach
循环中的对象。