Powershell 可重用SteppablePipeline代码随机中断
我一直在编写一个Powershell库,它围绕一个或两个函数使用了大量包装。多亏了a,我发现可以使用GetSteppablePipeline()方法进行包装。然而,我希望能够概括这段代码。通过谷歌搜索命令,我发现只有一两个样本被复制到了死亡状态,但没有一个函数。所以我试过了。一开始它似乎很有效,下面的示例大致上就是我首先创建的。但当我开始愤怒地使用代码时,它似乎到处都被破坏了 如果你直接运行下面的程序,它工作正常。但是,如果在ISE中插入任何断点,它将出现错误,如“找不到驱动器。名为“function”的驱动器不存在”。如果将代码合并到任何其他脚本中,它也会出现看似不可理解的错误(例如,对象未被识别为Cmdlet)Powershell 可重用SteppablePipeline代码随机中断,powershell,Powershell,我一直在编写一个Powershell库,它围绕一个或两个函数使用了大量包装。多亏了a,我发现可以使用GetSteppablePipeline()方法进行包装。然而,我希望能够概括这段代码。通过谷歌搜索命令,我发现只有一两个样本被复制到了死亡状态,但没有一个函数。所以我试过了。一开始它似乎很有效,下面的示例大致上就是我首先创建的。但当我开始愤怒地使用代码时,它似乎到处都被破坏了 如果你直接运行下面的程序,它工作正常。但是,如果在ISE中插入任何断点,它将出现错误,如“找不到驱动器。名为“funct
这可能与作用域有关(我在脚本中多次遇到这个问题)。我尝试在调用和函数作用域之间移动CreateSteppablePipeline()函数的部分,但没有成功。@PetSerAl谢谢-成功了。我没有想到在PowerShell库文件中点源“private”函数。仅出于兴趣-您是如何想到这将是答案的?在不相关的事件中,我碰巧了解到
SteppablePipeline
如果不在创建它的范围内使用,就会出现此类问题。不过,我无法说出这种不良行为的确切情况。
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