I have a script function that calls. net to manipulate word documents. It works. Now I want to create a sub-thread to execute it, and then the main thread decides whether it completes or exceeds the specified time, and ends it after that time. As shown in the code,It does not execute functions in the block of $node code, but instead $task1 executes the cmdlet. Why is that? How can I fulfill my needs?
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{
}