Adding Suggestions to PowerShell Console

by Aug 19, 2013

Suggestions are little pieces of text that can appear next to a PowerShell error message to better explain what went wrong. Suggestions only work in the PowerShell console. They do not work in the ISE editor. There are only three suggestions hard-coded into PowerShell, but you can add more.

When you run this code in a PowerShell console, you now also get suggestions when you try and access a non-available computer using Get-WmiObject:

$PSType = [PSObject].Assembly.GetType('System.Management.Automation.HostUtilities', $true)
$suggestions = $PSType.GetField('suggestions', 'Static,NonPublic,GetField').GetValue($null) 

$NewSuggestion = 
@{
    Id = 4
    Category = 'Network Problem'
    MatchType = 'Dynamic'
    Rule = 
    {
        ($lastError -and
        ($lastError.FullyQualifiedErrorId -eq 'GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand') -and
        ($lastError.Exception.Message -like '*RPC*'))
    }
    Suggestion = 
    {
        'The remote computer does not answer. It either does not exist, or a firewall may block access. Also make sure you did not mistype the computer name.'
    }
    Enabled = $true
}


$null = $suggestions.Add($NewSuggestion)

This is what the result would look like:

PS> Get-WmiObject -Class Win32_BIOS -ComputerName DoesNotExist
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ Get-WmiObject -Class Win32_BIOS -ComputerName DoesNotExist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetW miObjectCommand
Suggestion [4,InvalidOperation]: The remote computer does not answer. It either does not exist, or a firewall may block access. Also make sure you did not mistype the computer name.

$NewSuggestion actually is a hash table. Rule holds a script block that gets evaluated, and if it returns $true, then PowerShell displays the suggestion. Since PowerShell needs to evaluate all rules on all suggestions, it is obvious that your rules should evaluate quickly, or else it would slow down PowerShell.

The particular rule in this example looks like this:

 Rule = 
    {
        ($lastError -and
        ($lastError.FullyQualifiedErrorId -eq 'GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand') -and
        ($lastError.Exception.Message -like '*RPC*'))
    }

It basically checks whether there was an error record and whether the error ID was related to Get-WmiObject. With this rule alone, the suggestion would appear with any error produced by Get-WmiObject. To make it more specific, the rule also checks whether the error message contains the word "RPC" which indicates that a remote computer was unavailable.

Twitter This Tip! ReTweet this Tip!