?
Solved

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

Posted on 2013-02-06
8
Medium Priority
?
3,175 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
8 Comments
 
LVL 16

Expert Comment

by:Rajitha Chimmani
ID: 38861547
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
ID: 38861586
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
ID: 38861614
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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 16

Expert Comment

by:Rajitha Chimmani
ID: 38861660
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
 
LVL 70

Expert Comment

by:Qlemo
ID: 38862008
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
ID: 38865256
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 70

Accepted Solution

by:
Qlemo earned 1000 total points
ID: 38866171
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
ID: 38866314
Thanks
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

800 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