Powershell. Using add-member within an array.

Status
Not open for further replies.

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Powershell. Using Add-member on elements in an array

I’m making a new Powershell inventory script. I already have one, but I’m fiddling with the arrays to see if I can make the code a little prettier. I can make variables that have custom members with the add-member command. An example:

Code:
$computer1 = new-object psobject
$computer1 | add-member –membertype NoteProperty –name Online –value NotSet
$computer1 | add-member –membertype NoteProperty –name HostName –value NotSet
$computer1 | add-member –membertype NoteProperty –name Serial –value NotSet

$computer2 = new-object psobject
$computer2 | add-member –membertype NoteProperty –name Online –value NotSet
$computer2 | add-member –membertype NoteProperty –name HostName –value NotSet
$computer2 | add-member –membertype NoteProperty –name Serial –value NotSet

$computer1.HostName = “PC15”
$computer1.Serial = “43251”
$computer2.Online = “N”
$computer2.Serial = “12345”

That’s easy enough, but I want to set it in an array named $hosts. To replicate the last 4 lines of the preceding code:
Code:
$hosts[0].HostName = “PC15”
$hosts[0].Serial = “43251”
$hosts[1].Online = “N”
$hosts[1].Serial = “12345”

So now how do I do that? I tried this:
Code:
$hosts=@([psobject])
foreach ($i in $hosts){
	$i | add-member –membertype NoteValue –name Online –value NotSet
	}

I figured that would run the Add-Member command on each element in the array. It didn’t produce any errors, but it didn’t add an Online member to the elements.

I found a more complicated way that added variables with custom members to an array”

Code:
$computer1 = new-object psobject
$computer1 | add-member –membertype NoteProperty –name Online –value NotSet
$computer1 | add-member –membertype NoteProperty –name HostName –value NotSet
$computer1 | add-member –membertype NoteProperty –name Serial –value NotSet

$computer2 = new-object psobject
$computer2 | add-member –membertype NoteProperty –name Online –value NotSet
$computer2 | add-member –membertype NoteProperty –name HostName –value NotSet
$computer2 | add-member –membertype NoteProperty –name Serial –value NotSet

$hosts = @([psobject])
$hosts += $computer1
$hosts += $computer2

$hosts[0].HostName = “PC15”
$hosts[0].Serial = “43251”
$hosts[1].Online = “N”
$hosts[1].Serial = “12345”

This works. The values of $computer1 and $computer2 are fed into $hosts[0] and $hosts[1], custom members and all. But I need to iterate this n times, and I don’t know the value of n. So I made a $placeholder variable that would change within a loop.
The following code uses a for loop to change the value of $placeholder 10 times and add those values to $hosts 10 times.
Code:
Clear
$hosts=@([psobject])
$place = new-object psobject
$place | add-member –membertype NoteProperty –name Number –Value NotSet
$place | add-member –membertype NoteProperty –name HostName –Value NotSet
For($j=0;$j –le 9;$j++){
	$place.Number = $j
	$place.HostName = “Computer $j”
	$hosts += $place
	“-------------“
	“Iteration $j. Printing current values for place and hosts”
	“Place”
	$place
	“Hosts”
	$hosts[$j]
	}
“Completed for loop.”
“Value of Hosts array”
$hosts

This is the part that I don’t understand. In the middle of the loop, everything matches up. This is the output I see:
Code:
-------------
Iteration 0. Printing current values for place and hosts
	Place
0     Computer 0
	Hosts
0	Computer 0
-------------
Iteration 1. Printing current values for place and hosts
	Place
1     Computer 1
	Hosts
1	Computer 1

And so on. $place gets updated, and $hosts get a new entry.
But as it exits out of the loop, all elements of $hosts get the same value. This is the final output:
Code:
Value of Hosts array
5     Computer 5
5     Computer 5
5     Computer 5
5     Computer 5
5     Computer 5
5     Computer 5

WTF? Each iteration of the loop adds a new element to the array. But then each element takes on the current value of $place. I want each element to get set once and stay that way.

Is each element a kind of pointer? Forgive me if I have the wrong terminology. When I write “$hosts += $place” does that make the new element point to $place? How do I assign to it the value of $place and not $place itself? Any assistance would be greatly appreciated.
 

andrewme

Senator
7,120
Subscriptor
Put these lines inside the For loop:

Code:
$place = new-object psobject
$place | add-member –membertype NoteProperty –name Number –Value NotSet
$place | add-member –membertype NoteProperty –name HostName –Value NotSet

Looks like items are being put in the array by reference, and currently you are constructing and reusing a single object. Constructing a new object in each iteration will fix this.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
andrewme":2rf40pgi said:
Put these lines inside the For loop:

Code:
$place = new-object psobject
$place | add-member –membertype NoteProperty –name Number –Value NotSet
$place | add-member –membertype NoteProperty –name HostName –Value NotSet

Looks like items are being put in the array by reference, and currently you are constructing and reusing a single object. Constructing a new object in each iteration will fix this.

Thanks. I'll try putting it inside the loop so I make a new object each time.

Regarding the for loop itself, that's just for testing. My hope is to make a series of for-each loops for every member I want to add. Something like:

Code:
foreach $i in $hosts{
     test-connection $i 
     modify $i.online with if-else
     }

foreach $i in $hosts{
     get-wmi 
     modify $i.hostname with if-else
     }

And so on until each element has long line of members that I can dump into a spreadsheet. It's a poor man's inventory. I need a way to create this array with all the right members before I start all the foreach's.

BTW, I know there a million freeware programs that could do this more thoroughly and with much less effort. I'm doing this more for learning than convenience.
 

daishi

Ars Legatus Legionis
10,387
daishi":jal41o33 said:
Have you tried?

Code:
$hosts|foreach-object{$_|add-member -membertype noteproperty -name online -value notset}


I generally don't find a need to use traditional for loops in powershell (or arrays). I generally just work with foreach and collections of objects

Should probably make sure my code works before I post. Above code doesn't add any members, however the below does (which is how I normally handle the situation)

Code:
$hosts2=$hosts|foreach-object{$_|add-member -type noteproperty -name blah -value 23;$_}
$hosts2|get-member
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Richard Berg":3d5f7onb said:
A series of loops sounds even lamer. Have you heard of the pipeline?

I still need a for-each loop for each host in the array

for-each($h in $hosts){
get-wmi blah | $h.hostname
get-wmi blah | $h.processor
}

Unless you're referring to using "%" instead of "for-each". I prefer to spell out the whole line to make it easier to read.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
andrewme":3tp59c5u said:
Put these lines inside the For loop:

Code:
$place = new-object psobject
$place | add-member –membertype NoteProperty –name Number –Value NotSet
$place | add-member –membertype NoteProperty –name HostName –Value NotSet

Looks like items are being put in the array by reference, and currently you are constructing and reusing a single object. Constructing a new object in each iteration will fix this.

This did it. I created the new object inside the loop (thus creating a brand new one each time), and each array element took on the value of the object, not a reference to the object.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Is it better to store this kind of data in a 2-dimensional array or in members of a one-dimensional array? That is, which of the following two examples is better?
Code:
$hosts[10][0]="192.168.1.4"
$hosts[10][1]="Computer1"
$hosts[10][2]="Online"

OR

$hosts[10].ip="192.168.1.4"
$hosts[10].hostname="Computer1"
$hosts[10].status="Online"
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
I usually just break it out into a function if I'm going to be using it more than once.

Code:
function New-Computer($Online, $HostName, $Serial) {
  $computer = new-object psobject
  $computer | add-member –membertype NoteProperty –name Online –value $Oneline
  $computer | add-member –membertype NoteProperty –name HostName –value $HostName
  $computer | add-member –membertype NoteProperty –name Serial –value $Serial
}

$computer1 = New-Computer -Online "foo" -HostName "bar" -Serial "baz"

Also, "the powershell way" is to favor piping things to ForEach-Object in favor of "foreach ($item in $collection)". Though I also find it useful to copy $_ to a meaningful variable for readability.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Is it better to store this kind of data in a 2-dimensional array or in members of a one-dimensional array? That is, which of the following two examples is better?
Definitely the 2nd one. Don't use arrays to hold data that has internal structure. "What does field #5 mean again?" will drive you crazy.

Even the "outer" data structure could be a hashtable if the data has a natural key, like hostname. But that's going too far -- should a different key become convenient later, you'll have to write an annoying pivot routine. Rich objects gathered into a vanilla array is usually the best compromise between structure and genericity. Especially in Powershell, where the "use pipes to unroll a collection" idiom is so strongly ingrained. (hashtables are not unrolled by default)
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Also, "the powershell way" is to favor piping things to ForEach-Object in favor of "foreach ($item in $collection)".
Even that should be considered a compromise. Cmdlets should be designed to accept pipelined collections natively.

Guess my posts have been too oblique. Luckily I'm working at home today, so I can bang out some working examples:
Code:
# several members, one pipe
function New-Computer($Online, $HostName, $Serial) {
    New-Object psobject |
        Add-Member NoteProperty Online $Online -PassThru |
        Add-Member NoteProperty HostName $HostName -PassThru |
        Add-Member NoteProperty Serial $Serial -PassThru
}

# ...but do we even need it?  probably not...

$hostnames = # some query.  use Get-QADObject, or the native Get-ADObject available in 2008 R2.

# gwmi takes arrays.  not via pipeline, but that's probably clearer anyhow.
$biosInfo = Get-WmiObject Win32_BIOS SerialNumber, Manufacturer -ComputerName $hostnames
Just need to zip up the property bags (pairwise) and project out the field names you want. Built in fns are kind of lame, but alternatives are easy to find:

Zip: http://dougfinke.com/blog/index.php/200 ... -together/
Project: http://dmitrysotnikov.wordpress.com/201 ... roperties/

Or, instead of conjuring up brand new PSObjects, you could add the desired Bios properties to the AD objects (or vice versa). This guy has the right idea. Maybe something like this:
Code:
filter Extend-ADObjectWithBios {
    $BiosInfo = Get-WmiObject Win32_BIOS SerialNumber, Manufacturer -ComputerName $_.DnsName
    $_ |
        Add-Member NoteProperty Serial $BiosInfo.Serial -PassThru |
        Add-Member NoteProperty Manufacturer $BiosInfo.Manufacturer -PassThru
}

$AllInfo = Get-ADObject ... | Extend-ADObjectWithBios

Wonder if anyone's written a generalized Join-Object cmdlet... (Probably not; the Powershell syntax for lambdas is awful.)
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
Looks like the OPs issue has been solved, but I am kinda shocked no one has mentioned the new PowerShell 2 Object Creation syntax yet in this thread.

I hate the method commonly seen:
Code:
New-Object psobject |
        Add-Member NoteProperty Online $Online -PassThru |
        Add-Member NoteProperty HostName $HostName -PassThru |
        Add-Member NoteProperty Serial $HostName -PassThru

Instead, its much nicer in Powershell 2 to pass in a hash for your properties:
Code:
New-Object psobject -Property @{
        Online = $Online
        HostName = $HostName 
        Serial = $HostName 
}

I find the second to be much clearer and less wordy.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
tinyMan":3g5yfwno said:
Looks like the OPs issue has been solved, but I am kinda shocked no one has mentioned the new PowerShell 2 Object Creation syntax yet in this thread.

I hate the method commonly seen:
Code:
New-Object psobject |
        Add-Member NoteProperty Online $Online -PassThru |
        Add-Member NoteProperty HostName $HostName -PassThru |
        Add-Member NoteProperty Serial $HostName -PassThru

Instead, its much nicer in Powershell 2 to pass in a hash for your properties:
Code:
New-Object psobject -Property @{
        Online = $Online
        HostName = $HostName 
        Serial = $HostName 
}

I find the second to be much clearer and less wordy.

I'm gonna fiddle around with that. Due to a job change, I haven't regularly used Powershell for about 2 years, and most of my knowledge is from version 1. I'm relearning.

Powershell's method for adding members to array elements is terribly akward. The fact that I have to make a placeholder variable inside a for loop and add members to each individual element is crazy. I think I should be able to just use add-member on the array itself, and any elements should inherit those members.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Richard Berg":x6nyj51f said:
Sheesh, this *again*?

Code:
# the pipeline. It works, bitches
$extendedArr = $myArray | add-member NoteProperty $key $value -PassThru

Richard, that seems to replace the entire array with just one member. I don't think you're wrong; I think I'm missing something and I hope you can explain.
I made a short script with the following code. It incorporates your snippet:
Code:
#Test. Adding three members to each element of an array. Amem, Bmem, and Cmem (as if they were $a[0].cpu, $a[0].ram, and $a[0].hd
$aa = @(0..20) #Make an empty array with 20 elements. I tried this with $aa=([psobject]0..20) and got the same results

$ab = $aa | add-member -MemberType NoteProperty -Name Amem -Value NoteSet -PassThru #Copy RichardBerg's example three times.
$ab = $aa | add-member -MemberType NoteProperty -Name Bmem -Value NoteSet -PassThru 
$ab = $aa | add-member -MemberType NoteProperty -Name Cmem -Value NoteSet -PassThru

$ab[10] | get-member #See if amem, bmem, and cmem are all members

The above code results in each element of $ab having one member: cmem. amem and bmem are overwritten by subsequent lines. It won't add multiple members to each element of an array.

EDIT: Disregard.
I didn't put all the add-member commands into one line. I rewrote the script as follows:
Code:
$aa=$null #To make a fresh start
$aa = @(0..20) 
$aa = $aa | add-member -MemberType NoteProperty -Name Amem -Value NoteSet -PassThru ` #Copy RichardBerg's example three times.
| add-member -MemberType NoteProperty -Name Bmem -Value NoteSet -PassThru `
| add-member -MemberType NoteProperty -Name Cmem -Value NoteSet -PassThru

$aa[10] | get-member #See if amem, bmem, and cmem are all members. And they are!!!!!

That code, with add-member commands repeated in the same line (note the `) works great. Thanks Richard! :)
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Pont":s9lxv7ia said:
I think I should be able to just use add-member on the array itself, and any elements should inherit those members.
And what if you wanted to add members to the array itself and not the individual items?

What's so hard about
Code:
$myArray | ForEach-Object { $_ | Add-Member ... }

Pont, that doesn't work. I wrote the following short script:
Code:
clear
$aa = @(0..20) #Also tried with $aa=@([psobject]0..20)
$aa | Foreach-object { $_ | Add-Member -MemberType noteproperty -Name Amem -Value Not Set -PassThru} #Tried with and without -PassThru
$aa | Foreach-object { $_ | Add-Member -MemberType noteproperty -Name Bmem -Value Not Set -PassThru}
$aa | Foreach-object { $_ | Add-Member -MemberType noteproperty -Name Cmem -Value Not Set -PassThru}
$aa[10] |get-member

This did not add members to either $aa or any elements of $aa.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
The above code results in each element of $ab having one member: cmem. amem and bmem are overwritten by subsequent lines. It won't add multiple members to each element of an array.
Did you expect something different?

Code:
$aa = 10
$ab = $aa + 1
$ab = $aa + 2
$ab = $aa + 3
$ab                 # surely this prints 13, not 16?

See also: mutable variables considered harmful.

I think you meant to write:
Code:
$ab = 0..20 |
    add-member ...amem... |
    add-member ...bmem... |
    add-member ...cmem...

Of course, the PS 2.0 hashtable syntax is nicer still.
 
Status
Not open for further replies.