原始脚本的问题在于您的 foreach 循环中有 Export-Clixml。除此之外,你不应该这样做:
$xml += New-Object -TypeName PSObject -Property $Prop
如果您希望将这些对象存储在数组中以供以后使用,这要快得多:
$xml =
foreach ($User in (get-AdUser -filter * -SearchBase "OU=Path,DC=Domain,DC=Local" -Property *)){
$DisplayName = $User.DisplayName
$EmailAddress = $User.EmailAddress
$OfficePhone = $User.OfficePhone
$MobilePhone = $User.MobilePhone
$Office = $User.Office
$Department = $User.Department
$Prop=[ordered]@{
"DisplayName" = $DisplayName
'EmailAddress' = $EmailAddress
'OfficePhone' = $OfficePhone
'MobilePhone' = $MobilePhone
'Office' = $Office
'Department' = $Department
}
New-Object -TypeName PSObject -Property $Prop
}
$xml | Export-Clixml W:\skripts\OutFile.xml
如果您只需要导出文件,则根本不需要 $xml 变量。只需将整个 foreach 循环包装在一个子表达式中,然后将其直接通过管道传输到您的导出 cmdlet:
$(foreach ($User in (get-AdUser -filter * -SearchBase "OU=Path,DC=Domain,DC=Local" -Property *)){
$DisplayName = $User.DisplayName
$EmailAddress = $User.EmailAddress
$OfficePhone = $User.OfficePhone
$MobilePhone = $User.MobilePhone
$Office = $User.Office
$Department = $User.Department
$Prop=[ordered]@{
"DisplayName" = $DisplayName
'EmailAddress' = $EmailAddress
'OfficePhone' = $OfficePhone
'MobilePhone' = $MobilePhone
'Office' = $Office
'Department' = $Department
}
New-Object -TypeName PSObject -Property $Prop
}) | Export-Clixml W:\skripts\OutFile.xml
如果您不更改任何属性名称,则可以将整个内容替换为:
$props = 'DisplayName','EmailAddress','OfficePhone','MobilePhone','Office','Department'
get-AdUser -filter * -SearchBase "OU=Path,DC=Domain,DC=Local" -Property $props |
select $props | Export-Clixml W:\skripts\OutFile.xml