Link to home
Start Free TrialLog in
Avatar of bndit
bndit

asked on

Powershell: Export System.Collections.ArrayList with hashtable values to CSV

I have a script that creates AD accounts. I use a Collections.ArrayList object to collect the AD account attributes that I used to create the account. However, I can't export the contents of the ArrayList to a CSV file. I suspect it has to do with the fact that there's a hashtable inside the collection. How can I expand it?
$newADAccounts = New-Object System.Collections.ArrayList

# File contains user values
$users = Import-csv c:\temp\users.csv

# Create AD user
$userInfo = @{}

foreach ($user in $users) {

	$userInfo = @{
		FirstName = $user.FirstName
		LastName = $user.LastName
		ObjectAttributes = @{
			extensionAttribute1 = $user.SomeValue
			extensionAttribute2 = $user.SomeOtherValue
		}
	}
	$createdUser = New-QADUser @userInfo
	# Collect created users
	$newADAccounts.Add($createdUser)
}

# This does not work
$newADAccounts | 
Select-Object * |
Export-Csv C:\temp\adaccounts.csv -notype

# Output expected
FirstName,LastName,ExtensionAttribute1,ExtensionAttribute2

# Instead I get output like this
#  IsReadOnly	IsFixedSize	IsSynchronized	Keys	Values	SyncRoot	Count
# FALSE	FALSE	FALSE	System.Collections.Hashtable+KeyCollection	System.Collections.Hashtable+ValueCollection	System.Object	21

Open in new window

Avatar of Rajitha Chimmani
Rajitha Chimmani
Flag of United States of America image

I think you have written complicated script to achieve a simple task. Is it mandatory to use hashtables in the script? If not let me know what is the task that you are trying to achieve.

From the script it appears you are trying to create new AD user?? Are the users being created? You have not specified the password for these AD accounts???
Avatar of bndit
bndit

ASKER

I only provided a very oversimplified code snippet (omitted many calculated values, etc. etc); let's assume AD accounts ARE being created successfully.
Or, you can just change the lines 19-21
# Change this 
$createdUser = New-QADUser @userInfo
# Collect created users
$newADAccounts.Add($createdUser)

# To this
#$createdUser = New-QADUser @userInfo
# Collect created users
$newADAccounts.Add($userInfo)

Open in new window

*However, I dont know what the difference between using the results of the New-QADUser cmdlet vs using the hashtable $userInfo would be.
My main goal really is to run this script against AD, calculate values (sorta like "What-if" but giving me real values ie. "John Doe" exists in AD and thus his DN would be "CN=John Doe1"), and export those real values to a file without making any changes to AD just yet.
Avatar of bndit

ASKER

Ok, I found a piece of code that helps me export the main hashtable $userInfo but not the nested hashtable "ObjectAttributes"
$newADAccounts | % {
   New-Object PSObject -Property $_
| Export-Csv c:\temp\adaccounts.csv -NoTypeInformation

Open in new window

Any idea how I can expand the nested hashtable?
I am afraid you will not be able to select the objects directly and export to csv as it is a collection of objects. You will have to use foreach loop to perform that. I have tried something like the below to display the contents of the hash table.
$ADinfo = @()
$newADAccounts | foreach {
$ADaccounts = New-Object System.Object
$ADaccounts | Add-Member -MemberType NoteProperty -value $_.FirstName -Name FirstName
$ADaccounts | Add-Member -MemberType NoteProperty -value $_.LastName -Name LastName
$_.ObjectAttributes | foreach{
$ADaccounts | Add-Member -MemberType NoteProperty -value $_.Extensionattribute1 -Name Extensionattribute1
$ADaccounts | Add-Member -MemberType NoteProperty -value $_.Extensionattribute2 -Name Extensionattribute2}
$ADinfo += $ADaccounts
}

$ADinfo | Export-csv <filename> -notype
Basically that (you can't do that) is correct. Nested objects cannot be "enrolled" properly into a CSV file (that is without loss of structure or information). You'll need to either "encode" them, like in a string as  "{value1, value2}", and then decode that on import again, or flatten the values as shown above.

Since you expect the properties to just be enrolled into properties, removing the hash container, it should as "easy" as this:
$newADAccounts | select `
     @{n='FirstName', e={$_.FirstName}},
     @{n='LastName', e={$_.LastName}},
     @{n='ExtensionAttribute1'; e={$_.ObjectAttributes.extensionAttribute1}},
     @{n='ExtensionAttribute2'; e={$_.ObjectAttributes.extensionAttribute2}} `
| export-csv -noType Output.txt

Open in new window

Avatar of bndit

ASKER

Thanks for the guidance, but even though hardcoding would solve my problem it's not easy due to the number of attributes. I was able to come up with something that helps me get where I want to get, but it's not robust enough to flatten out a hashtable with multiple levels. The basic logic that I'm thinking about would be...take a hashtable, look at its properties. If any of those properties remove it from the current hashtable. Do the same for any lower level hashtable found.
function Expand-Hash {
	Param(
		[Parameter()]
		[hashtable]
		$hash	
	)
	$obj = New-Object psobject -Property $hash
	$ht1 = $hash.clone()
	$ht2 = @{}
	$tmpht = @{}
	$finalht = @{}
	
	foreach($prop in $obj.psobject.properties)
	{
		$propName = $prop.Name
		$propValue = $prop.Value
				
		if ($propValue -is [hashtable])
		{
			$ht1.remove("$propName")
			$tmpht.add($propName,$propValue)
			$tmpht.Item("$propName").Keys | % {
				$ht2."$_" = $tmpht.Item("$propName").Item("$_")
			}
		}
	}
	return $ht1 + $ht2
}
$userCol = @()
$Newly_Created_ADUsers | % {
	$user = Expand-Hash $_
	$objTemp = New-Object PSObject -Property $user
	$userCol += $objTemp
}
$userCol | 
Export-Csv c:\temp\output.csv -NoTypeInformation

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bndit

ASKER

Thanks