Forum Discussion
Sushantjha
Sep 28, 2020Copper Contributor
bulk update extension attribute in AD
I have written below script to update the extension attribute and after updating I want the report in CSV. If I run till update it is working fine but when I am adding select-object to take the entries in CSV it is throwing an error.
Import-Csv -path c:\temp\SetExtAtt1.csv |ForEach-Object {
Set-ADComputer $_.samAccountName -replace @{
ExtensionAttribute4 = "$($_.ExtensionAttribute4)"
ExtensionAttribute6 = "$($_.ExtensionAttribute6)"|Select-Object @{Label = "Name";Expression = {$_.samAccountName}},
@{Label = "Attribute4";Expression = {$_.extensionAttribute4}},
@{Label = "Attribute6";Expression = {$_.extensionAttribute6}}|Export-Csv C:\Temp\OwnerTest2.csv -Append -NoTypeInformation
}
}
- farismalaebSteel Contributor
To Export the Hash table you will need to use the GetEnumerator()
https://tommymaynard.com/hash-table-to-csv-2018/
I recommend that you replace the hash table with PSObject
- SushantjhaCopper Contributor
I have made the below changes but each iteration of foreach loop saves to $Output. It overwriting what was there previously, i.e., the previous iteration. Which means that only the very last iteration is saved to $Output and exported.
Import-Csv -path c:\temp\SetExtAtt1.csv |ForEach-Object {$Output = @()Set-ADComputer $_.samAccountName -replace @{ExtensionAttribute4 = "$($_.ExtensionAttribute4)"ExtensionAttribute6 = "$($_.ExtensionAttribute6)"}$Output =New-Object -TypeName PSObject -Property @{samAccountName = "$($_.samAccountName)"ExtensionAttribute4 = "$($_.ExtensionAttribute4)"ExtensionAttribute6 = "$($_.ExtensionAttribute6)"}}$Output | Export-Csv C:\Temp\OwnerTest2.csv -NoTypeInformation -Encoding UTF8 -Append- farismalaebSteel Contributor
Yes, sure as the $Output=@() is inside the loop and is being reset everytime, a very quick fix will be to add a new variable at the top
and once the $output have the result, add it to the variable
try the code below and get the result from $allresult variable.
$allresult=@() Import-Csv -path C:\123\EXDB1.csv |ForEach-Object { $Output = @() Set-ADComputer $_.samAccountName -replace @{ ExtensionAttribute4 = "$($_.ExtensionAttribute4)" ExtensionAttribute6 = "$($_.ExtensionAttribute6)"} $Output =New-Object -TypeName PSObject -Property @{ samAccountName = "$($_.samAccountName)" ExtensionAttribute4 = "$($_.ExtensionAttribute4)" ExtensionAttribute6 = "$($_.ExtensionAttribute6)" $allresult=$output } } $Output | Export-Csv C:\Temp\OwnerTest2.csv -NoTypeInformation -Encoding UTF8 -Append