我有一个调用的脚本函数。net 来操作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{
}