我有一个脚本函数可以调用。网来操纵Word文档。有用。现在,我想创建一个子线程来执行它,然后主线程决定它是完成还是超过指定的时间,并在该时间之后结束。 如代码中所示,它不执行$ node代码块中的函数,而是$ task1执行cmdlet。这是为什么?我该如何满足我的需求?
try{
# $cb is a instance of class,scan is the function I want to invoke.
$code = { $cb.Scan($PrepareFileName, $NailDirName, $HtmlFileName) }
# $task1 = { Start-Sleep -Seconds 9; Get-Service }
$newThread = [PowerShell]::Create().AddScript($code)
$handleTh = $newThread.BeginInvoke()
$nTimes = 0;
do
{
$nTimes++;
if($handleTh.IsCompleted -or $nTimes -gt 10)
{
break;
}
Start-Sleep -Milliseconds 500
} while($true)
$newThread.EndInvoke($handleTh)
$newThread.Runspace.Close()
$newThread.Dispose()
}catch{
}
答案 0 :(得分:0)
您需要创建一个runspace
,并将其创建到PowerShell对象。检查此microsoft“教程”以正确使用运行空间。 link还说明了如何使用运行空间池和脚本块参数。
try{
# $cb is a instance of class,scan is the function I want to invoke.
$code = {
# Update 1, added parameter
param($cb)
$cb.Scan($PrepareFileName, $NailDirName, $HtmlFileName)
}
# Create a runspace
$runspace = [runspacefactory]::CreateRunspace()
# Update 1, inject parameter
$newThread = [PowerShell]::Create().AddScript($code).AddParameter(‘cb’,$callback)
# Add the runspace
$newThread.Runspace = $runspace
$runspace.Open()
$handleTh = $newThread.BeginInvoke()
$nTimes = 0;
do
{
$nTimes++;
if($handleTh.IsCompleted -or $nTimes -gt 10)
{
break;
}
Start-Sleep -Milliseconds 500
} while($true)
$newThread.EndInvoke($handleTh)
$newThread.Dispose()
}
catch{
}
希望有帮助。