Solved

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

Posted on 2013-02-06
8
2,691 Views
Last Modified: 2013-02-07
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

0
Comment
Question by:bndit
  • 4
  • 2
  • 2
8 Comments
 
LVL 16

Expert Comment

by:Rajitha Chimmani
Comment Utility
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???
0
 
LVL 2

Author Comment

by:bndit
Comment Utility
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.
0
 
LVL 2

Author Comment

by:bndit
Comment Utility
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?
0
 
LVL 16

Expert Comment

by:Rajitha Chimmani
Comment Utility
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
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
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

0
 
LVL 2

Author Comment

by:bndit
Comment Utility
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

0
 
LVL 68

Accepted Solution

by:
Qlemo earned 250 total points
Comment Utility
This function will flatten out the hash table. But remember that the sequence of properties in a hash table is arbitrary.
function Expand-Hash ( [hashtable] $hash, [PSobject] $obj = (New-Object PSObject) )
{
  $hash.GetEnumerator() | % {
    if ($_.Value -is [hashtable]) {
      Expand-Hash $_.Value $obj | Out-Null
    } else {
      $obj | Add-Member NoteProperty $_.Key $_.Value
    }
  }
  $obj
}

Open in new window

0
 
LVL 2

Author Closing Comment

by:bndit
Comment Utility
Thanks
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Why would I want to create a function for tracking messages? I am glad you asked. As with most monotonous/routine tasks, human error tends to creep in after doing the same task over and over again. By creating a function, you load the function once…
This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now