When designing PowerShell functions, you can improve usability tremendously by adding clever argument completion IntelliSense.

To compose argument IntelliSense completion, you can equip each parameter of your function with a piece of PowerShell code that dynamically composes the IntelliSense list. Of course, the code you use should be quick to compute so IntelliSense won’t time out.

If you need to add methods (commands) to your object, add them via Add-Member:

function Get-MyLocalUser
{
  #Content
  param
  (
    [String]
    [Parameter(Mandatory)]
    [ArgumentCompleter({
          # receive information about current state:
          param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
    
          Get-LocalUser |
          ForEach-Object { 
            $name = $_.Name
            $desc = $_.Sid    # showing SID as QuickTip
            [System.Management.Automation.CompletionResult]::new($name, $name, "ParameterValue", $desc)
          }
     })]
     $UserName
  )
  
  "You chose $UserName"

}

After you ran the code, in the interactive console type:

 
PS> Get-MyLocalUser -UserName 
 

Once you add a space after -UserName, IntelliSense kicks in and shows all local user names. When you select one of the IntelliSense items for a moment, the Quicktip displays the user SID.

This intelligent argument completion is defined inside the [ArgumentCompleter()] attribute. The code inside of it produces CompletionResult-objects, one per IntelliSense list item.




Twitter This Tip! ReTweet this Tip!

Anonymous