How to add properties to a PowerShell object from an array
I am still not sure completely, but if you are just focusing on the Add-Member
then consider the following.
$fieldsarray = "ID", "ContentTypeID", "ContentType", "Title", "Modified"$itemki = "1", "0x0108007345CD807822EA4E85691E5C642F3A27", "", "Task0", "11/24/2014 12:29:30 PM"$itemobj = New-Object pscustomobjectfor($k=0;$k -lt $fieldsArray.Count ; $k++){ $itemobj | Add-Member NoteProperty $fieldsarray[$k] $itemki[$k]}$itemobj
Notice the empty string entry in the array $itemki
. This would generate the output.
ID : 1ContentTypeID : 0x0108007345CD807822EA4E85691E5C642F3A27ContentType :Title : Task0Modified : 11/24/2014 12:29:30 PM
Change the ""
to an empty element: "1","0x0108007345CD807822EA4E85691E5C642F3A27",,"Task0","11/24/2014 12:29:30 PM"
, and you get this output:
ID : 1ContentTypeID : 0x0108007345CD807822EA4E85691E5C642F3A27ContentType : {Task0}Title : 11/24/2014 12:29:30 PMModified :
Which is wrong. Then if you change the empty element to $null
your output looks much like the first:
ID : 1ContentTypeID : 0x0108007345CD807822EA4E85691E5C642F3A27ContentType :Title : Task0Modified : 11/24/2014 12:29:30 PM
Concerning your output
You say you only get the last element when you do $itemobj
outside the loop. What does $itemobj
look like after each pass? for(;;){}
loops don't send data to the output stream in the same way that a ForEach-Object{}
would which is worth mentioning.
You could use a hash table instead of two arrays. It's very easy to create an object from a hash table. Here's an example:
$hash = @{ ID = '1' ContentTypeID = '0x0108007345CD807822EA4E85691E5C642F3A27' ContentType = '' Title = 'Task0' Modified = '11/24/2014 12:29:30 PM'}$Object = New-Object PSObject -Property $hash
Don't do a For loop, do a ForEach-Object loop. Something like:
$Object = New-Object PSObject$Array | ForEach{ Add-Member -InputObject $Object -NotePropertyName $_[0] -NotePropertyValue $_[1]}
That should do what you're looking for I think.