PoshCode Archive  Artifact [d671ad95bc]

Artifact d671ad95bcce6b221ee469916913a671beaf2474fd8119e656b2f186f301f9fb:

  • File New-ScriptCmdlet.ps1 — part of check-in [3187aa0256] at 2018-06-10 12:56:37 on branch trunk — A script to generate advanced functions that wrap cmdlets so you can tweak them, add features, etc. From the PowerShell Team Blog (user: unknown size: 1790)

# encoding: ascii
# api: powershell
# title: New-ScriptCmdlet
# description: A script to generate advanced functions that wrap cmdlets so you can tweak them, add features, etc. From the PowerShell Team Blog
# version: 0.1
# type: script
# license: CC0
# function: New-ScriptCmdlet
# x-poshcode-id: 1193
# x-archived: 2010-07-17T01:52:10
#
#
# http://blogs.msdn.com/powershell/archive/2008/05/09/fun-with-script-cmdlets.aspx
########################################################################################
# function New-ScriptCmdlet() {
[CmdletBinding(DefaultParameterSetName="Type")]
PARAM(
   [Parameter(ParameterSetName="Type",ValueFromPipeline=$true,Position=1)]
   [Type]
   $type
,
   [Parameter(ParameterSetName="CommandInfo",ValueFromPipeline=$true,Position=1)]
   [Management.Automation.CmdletInfo]
   $commandInfo
,
   [Parameter(Position=0)]
   [string]
   $name
)

    Process
    {
        if (! $type) {
            if ($commandInfo.ImplementingType) { $type = $commandInfo.ImplementingType }
        }

        if ((! $type) -and (! $commandInfo)) {
@"
$(if ($name) { 'function ' + $name + '() {' })
[CmdletBinding()]
param   ()
begin   {}
process {}
end     {}
$(if ($name) {'}' })
"@
        } else {
            if (! ($type.IsSubclassOf([Management.Automation.Cmdlet]))) {
                throw "Must provide a cmdlet to create a proxy"
            }

            $commandMetaData = New-Object Management.Automation.CommandMetadata $type
            $proxyCommand =
@"
$(if ($name) { 'function ' + $name + '() {' })
$([Management.Automation.ProxyCommand]::Create($commandMetaData))
$(if ($name) {'}' })
"@

            $executionContext.InvokeCommand.NewScriptBlock($proxyCommand)
        }
    }
#}