PoshCode Archive  Artifact [5a64f68a0d]

Artifact 5a64f68a0d57e527a5cb464ea3c64b5ab205fc2dfd8a9264db10164edca374b6:

  • File Add-Get-Help-Full.ps1 — part of check-in [d16ed61474] at 2018-06-10 13:31:54 on branch trunk — A crazy example of how you can extend PowerShell! This has two options for getting full help: (user: Joel Bennett size: 2194)

# encoding: ascii
# api: powershell
# title: Add ? Get-Help -Full
# description: A crazy example of how you can extend PowerShell! This has two options for getting full help:
# version: 0.1
# type: script
# author: Joel Bennett
# license: CC0
# x-poshcode-id: 3835
# x-archived: 2012-12-22T17:51:54
# x-published: 2012-12-19T11:44:00
#
# A PreCommandLookup handler which allows a leading ? to turn into Get-Help -Full. E.g.:  ?gc turns into Get-Help gc -Full.  This one works!
# A PostCommandLookup handler which adds a ubiquitous -?? parameter which is like the -? parameter that calls Get-Help, except this one calls Get-Help -Full. This works as a demo, but you can’t use it in real life, because the script block doesn’t work in pipelines.
# Works, Use That.
#
$executionContext.SessionState.InvokeCommand.PreCommandLookupAction = {
    param($CommandName, $CommandLookupEventArgs)

    if($CommandName.StartsWith("?")) {
        $RealCommandName = $CommandName.TrimStart("?")
        $CommandLookupEventArgs.CommandScriptBlock = {
            Get-Help $RealCommandName -Full
        ## Wrap it in a closure because we need $CommandName
        }.GetNewClosure()
    }
}


Write-Warning "DO NOT USE THIS POSTCOMMANDLOOKUPACTION EXCEPT FOR DEMONSTRATION"

$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
    param($CommandName, $CommandLookupEventArgs)

    # Only for interactive commands (and that doesn't include "prompt")
    # I should exclude out-default so we don't handle it on every pipeline, but ...
    if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) {
        ## Create a new script block that checks for the "-??" argument 
        ## And if -?? exists, calls Get-Help -Full instead
        ## Otherwise calls the expected command
        $CommandLookupEventArgs.CommandScriptBlock = {
            if($Args.Length -eq 1 -and $Args[0] -eq "-??") {
                Get-Help $CommandName -Full
            } else {
                & $CommandName @args
            }
        ## Wrap it in a closure because we need $CommandName
        }.GetNewClosure()
    }
}