I need to export some attributes from active directory user accounts to xml containg Displayname, email, officephone, mobile, office and department. I got this powershell code
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
}
$obj = New-Object -TypeName PSObject -Property $Prop
$xml += $obj | Export-Clixml W:\skripts\OutFile.xml
}
But the result in the xml file only contain one user, the last one. I cant figure out where i do wrong.
Regards Niklas }
The problem with your original script is that you have your Export-Clixml inside your foreach loop. Beyond that, you shouldn't be doing this:
If you want those objects stored in an array to use later, this is much faster:
If all you need is the export file, you don't really need the $xml variable at all. Just wrap the whole foreach loop in a sub-expression and pipe that directly to your export cmdlet:
And if you're not changing any of the property names, the whole thing could be replaced with this: