PowerShell V2: Meet New-Object's Property parameter
I've stumbled upon blog post that talks about accessing remote registry, collecting "Automatic Update" configuration info and creating custom object to hold that data for further processing/formatting.
The author has used Add-Member cmdlet to add quite a bunch of NoteProperties to the custom object. In PowerShell V2 we can do it in much cleaner way, with less typing, using new New-Object's Property parameter that expects a hash table as a value, a hash table in which the keys are the names of properties or methods and the values are property values or method arguments.
Let's rewrite a function.
function Get-WSUSRegKey {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true)]
[String[]]$ComputerName = $env:computername
)
PROCESS {
$ComputerName | ForEach-Object {
# open remote registry key
$rootKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$_)
# open subkey WindowsUpdate and its subkey AU
$regKey0 = $rootKey.OpenSubKey("Software\policies\Microsoft\Windows\WindowsUpdate\")
$regKey1 = $rootKey.OpenSubKey("Software\policies\Microsoft\Windows\WindowsUpdate\" + $($regKey0.GetSubKeyNames()))
# create an empty hash table
$ht = @{}
# enumerate value names in both subkeys and populate hash table with name/value pairs
$regKey0.GetValueNames() | ForEach-Object {$ht.$_ = $regKey0.GetValue($_)}
$regKey1.GetValueNames() | ForEach-Object {$ht.$_ = $regKey1.GetValue($_)}
# this will add ComputerName NoteProperty to our object
$ht.ComputerName = $_
# and finally, create an object using the data stored in a hash table
New-Object PSObject -Property $ht
}
}
}
Two usage examples:
PS C:\> $servers = 'server1','server2','server3'
PS C:\> Get-WSUSRegKey -ComputerName $servers
PS C:\> $servers | Get-WSUSRegKey | Format-Table ComputerName,WUServer