Wednesday, May 18, 2016

Finding Type Information in PowerShell

On frequent occasions, I find myself using a cmdlet and needing more information about the objects that cmdlet produces. The details are in Microsoft’s MSDN library, but it can be hard to use the GUI to find it. Fortunately, I found a cool way of dealing with this. I found the trick on the Internet but I really can not remember where I found it.

The trick is simple: I use some Type XML to extend all objects with a new script method called MSDN. If I create an object – I can assign it to a variable and just call the .MSDN() method on any occurrence.  Suppose I did a Get-ChildItem against the Certificate Provider and needed more details on the object returned. I just do this:

$Certs = Get-ChildItem Cert:\CurrentUser\My
$Certs[0].MSDN()

The MSDN() method, something I’ve added in, then brings up Internet Explorer and nvigates to the appropriate page in the MSDN library. Which is: https://msdn.microsoft.com/library/System.Security.Cryptography.X509Certificates.X509Certificate2.ASPX.

But how did that method come about – you might ask! Easy – it’s just a bit of type XML I add to each system I use. I just add an xml file and reference it in my PowerShell profile. The XML file looks like this:

<Types>
  <Type>
    <Name>System.Object</Name>
    <Members>
      <ScriptMethod>
        <Name>MSDN</Name>
        <Script>
           if (($global:MSDNViewer -eq $null) –or
              ($global:MSDNViewer.HWND -eq $null))
           {$global:MSDNViewer = new-object -ComObject InterNetExplorer.Application}
              $Uri = "
http://msdn2.microsoft.com/library/" + $this.GetType().FullName + ".ASPX"
              $global:MSDNViewer.Navigate2($Uri)
              $global:MSDNViewer.Visible = $TRUE
      </Script>
      </ScriptMethod>
    </Members>
  </Type>
</Types>

I have saved this into a file (I saved it as c:\foo\my.types.ps1.xml) then in each PowerShell profile I just add it in:

Update-TypeData -appendPath C:\foo\my.types.ps1xml

And from then on, you can just use the MSDN method on just about any type. It’s not perfect – sadly there are types/classes that do not appear documented in MSDN (or at least now where this little XML trick can find it).

If you know where this came from, Please comment – I just can’t remember where I found it!

1 comment:

Unknown said...

Maybe http://www.leeholmes.com/blog/2006/12/04/add-custom-methods-and-properties-to-types-in-powershell/