Solved

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

Posted on 2013-02-06
8
2,814 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
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
Problems using Powershell and Active Directory?

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 69

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 69

Accepted Solution

by:
Qlemo earned 250 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

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

Question has a verified solution.

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

Are you one of those front-line IT Service Desk staff fielding calls, replying to emails, all-the-while working to resolve end-user technological nightmares? I am! That's why I have put together this brief overview of tools and techniques I use in o…
Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

777 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