Alias property and ps1xml to rescue!

I work very often with WMI. What I do not like about it is the fact that I need to do something with that ugly __SERVER automatic property to make output nice. Let’s say I want to get serials from bunch of computers:

$Computers = 'WAR000260 PL-WAR-AP001 PL-WAR-VFP001'.Split()
Get-WmiObject -ComputerName $Computers -Class Win32_BIOS | select SerialNumber, ComputerName

That syntax won’t work. And yes, there is from time to time some property that returns remote computer name. But it’s not consistent in any way. I usually just use some hashtable tricks to change __SERVER into something more friendly. But that’s not the only way. For me easiest way would be to simply have consistent property that would give me what I need – ComputerName. Logic behind it is very simple. Since extending types in PowerShell is easy (once you figure out XML structure), why not add it at this level? XML for that is just few lines:

 

<?xml version=”1.0″ encoding=”utf-8″ ?>

<Types>

<Type>

<Name>System.Management.ManagementObject</Name>

<Members>

<AliasProperty>

<Name>ComputerName</Name>

<ReferencedMemberName>__SERVER</ReferencedMemberName>

</AliasProperty>

</Members>

</Type>
</Types>

All you need to do is save it as .ps1xml file, and load it – either before or after default (MS) type extensions. I’m loading it before:

Update-TypeData -PrependPath (Join-Path (Split-Path $profile) WMI.types.ps1xml)

Once it is done _all_ classes from WMI will get new AliasProperty ComputerName equal to __SERVER. And that (if you haven’t filtered it out) should always be there:

Get-WmiObject -Class Win32_BIOS | Get-Member ComputerName

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_BIOS

Name         MemberType    Definition
----         ----------    ----------
ComputerName AliasProperty ComputerName = __SERVER

No more hashtables, no more looking at ugly __SERVER. I only wonder why PowerShell team haven’t done it. Probably I just broke something important.. But it looks nice, right? 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s