[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

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

Posted on 2013-02-06
8
Medium Priority
?
3,378 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
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
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 71

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 71

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

Looking for the Wi-Fi vendor that's right for you?

We know how difficult it can be to evaluate Wi-Fi vendors, so we created this helpful Wi-Fi Buyer's Guide to help you find the Wi-Fi vendor that's right for your business! Download the guide and get started on our checklist today!

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
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…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

650 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