Scripting Games Commentary: VIII Creating Objects
I saw a lot of code like this during the games
| 001 002 003 004 005 006 007 008 009 010 011
| $comp = Get-WmiObject -Class Win32_ComputerSystem $os = Get-WmiObject -Class Win32_OperatingSystem $myobject = New-Object -TypeName PSObject Add-Member -InputObject $myobject -MemberType NoteProperty -Name "Make" -Value $comp.Manufacturer Add-Member -InputObject $myobject -MemberType NoteProperty -Name "Model" -Value $comp.Model Add-Member -InputObject $myobject -MemberType NoteProperty -Name "OS" -Value $os.Caption Add-Member -InputObject $myobject -MemberType NoteProperty -Name "SP" -Value $os.CSDVersion $myobject |
Get some stuff, create an object and add the properties. That’s a lot of typing. A slightly easier way is like this
| 001 002 003 004 005 006 007 008 009 010 011
| $comp = Get-WmiObject -Class Win32_ComputerSystem $os = Get-WmiObject -Class Win32_OperatingSystem $myobject = New-Object -TypeName PSObject $myobject | Add-Member -MemberType NoteProperty -Name "Make" -Value $comp.Manufacturer -PassThru | Add-Member -MemberType NoteProperty -Name "Model" -Value $comp.Model -PassThru | Add-Member -MemberType NoteProperty -Name "OS" -Value $os.Caption -PassThru | Add-Member -MemberType NoteProperty -Name "SP" -Value $os.CSDVersion $myobject |
This time we get the pipeline to do some of the work for us using the –passthru parameter to keep passing the object to the next Add-Member
But wait
There’s an even better and easier way
| 001 002 003 004 005 006 007 008 009 010 011
| $comp = Get-WmiObject -Class Win32_ComputerSystem $os = Get-WmiObject -Class Win32_OperatingSystem $myobject = New-Object -TypeName PSObject -Property @{ Make = $comp.Manufacturer Model = $comp.Model OS = $os.Caption SP = $os.CSDVersion } $myobject |
Use the –property parameter on new-object and create a hash table of the property names and values. The hash table can be created earlier is required.
Recommendation – create the properties using the hash table method. Set the values at creation if you know them otherwise simple set as they become available.
Keep the typing down, keep the bugs down and keep the Power up.