我一直在编写一个Powershell库,该库在一个或两个函数周围使用了很多包装器。感谢previous question,我发现可以使用GetSteppablePipeline()方法进行包装。但是,我希望能够对此代码进行概括。谷歌搜索命令后,我发现只有一个或两个样本已被复制到死亡,但没有单个函数。所以我尝试了。它似乎起初很有效,下面的示例大致是我首先创建的。但是当我开始在愤怒中使用该代码时,它似乎到处都破裂了。
如果直接运行以下内容,则可以正常运行。但是,如果您在ISE中插入任何断点,它将以“找不到驱动器。名称为'function'的驱动器不存在”之类的错误断开。如果将代码合并到任何其他脚本中,它也会因看似无法理解的错误而中断(例如,Where-Object未被识别为Cmdlet)。
Function CreateSteppablePipeline
{
Param(
[Parameter(Mandatory = $true, Position = 0)]
[string]
$InnerFunctionName,
[Parameter(Mandatory = $true, Position = 1)]
[System.Collections.Generic.Dictionary`2[System.String,System.Object]]
$OuterPSBoundParameters,
[Parameter(Mandatory = $true, Position = 2)]
[System.Management.Automation.EngineIntrinsics]
$OuterExecutionContext,
[Parameter(Mandatory = $true, Position = 3)]
[System.Management.Automation.InvocationInfo]
$OuterMyInvocation
)
$outBuffer = $null
if ($OuterPSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$OuterPSBoundParameters['OutBuffer'] = 1
}
[System.Management.Automation.FunctionInfo] $wrappedCmd = $OuterExecutionContext.InvokeCommand.GetCommand($InnerFunctionName, [System.Management.Automation.CommandTypes]::Function);
[ScriptBlock] $scriptCmd = { & $wrappedCmd @OuterPSBoundParameters };
[System.Management.Automation.SteppablePipeline] $steppablePipeline = $scriptCmd.GetSteppablePipeline($OuterMyInvocation.CommandOrigin);
$steppablePipeline.Begin($OuterMyInvocation.ExpectingInput);
$steppablePipeline;
}
Function Inner
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, Position=0)]
[string] $ExParam,
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[string[]] $Value
)
Begin {
[int] $i = 0;
}
Process {
$i++;
ForEach ($myValue In $Value)
{
$myValue;
}
}
End {
$i;
$ExParam;
}
}
Function Outer
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, Position=0)]
[string] $ExParam,
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[string[]] $Value
)
Begin {
[System.Management.Automation.SteppablePipeline] $steppablePipeline = CreateSteppablePipeline "Inner" $PSBoundParameters $ExecutionContext $MyInvocation;
}
Process {
$steppablePipeline.Process($_) |
ForEach-Object {
$_ + " : Pipelined";
}
}
End {
$steppablePipeline.End()
}
}
Outer -ExParam 22 "Name1","Name2","Name3","Name4","Name5","Name6","Name7"
"Name1","Name2","Name3","Name4","Name5","Name6","Name7" | Outer -ExParam 22
这可能与范围界定有关(我在脚本中多次遇到此问题)。我尝试在调用和函数作用域之间移动CreateSteppablePipeline()函数的一部分,但是没有运气。