我有一个 powershell 脚本,它应该运行一个后台作业,直到用户决定它应该结束。后台作业是这个脚本块:
$block =
{
param(
[Parameter(Mandatory = $true, Position = 0, valueFromPipeline = $true)]
$Counters,
[Parameter(Mandatory = $true, Position = 1, valueFromPipeline = $false)]
[ref]$killSwitch,
[Parameter(Mandatory = $false, Position = 2, valueFromPipeline = $false)]
[long]$SampleInterval = 1000
)
[System.Diagnostics.Stopwatch]$sw = New-Object System.Diagnostics.StopWatch
$sw.Start()
$last = 0
$report = New-Object PSObject
$report | Add-Member -MemberType NoteProperty -Name Start -Value ([DateTime]::Now)
while(!$killSwitch)
{
if($sw.ElapsedMilliseconds -gt $last + $SampleInterval)
{
$rec = Get-CounterSample -counters $Counters
$report | Add-Member -MemberType NoteProperty -Name $sw.ElapsedMilliseconds -Value $rec
$last = $sw.ElapsedMilliseconds
}
}
$report | Add-Member -MemberType NoteProperty -Name End -Value ([DateTime]::Now)
return $report
}
如您所见,我试图传入一个布尔值 ( $killSwitch
) 作为While
在用户/调用者完成后停止循环的一种方式。我用以下方式调用它:
[bool]$kill = $false
$job = Start-Job -Name twProcMon -ScriptBlock $block -ArgumentList $Counters, ([ref]$kill), $SampleInterval
Read-Host
$kill = $true
Wait-Job $job
Receive-Job $job
我收到一个错误:
无法处理参数“killSwitch”上的参数转换。参数中需要引用类型。
如何通过引用代码块来传递布尔值,以便我可以从作业外部终止 while 循环?可能吗?