powershell - 为什么PowerShell创建的线程不能执行脚本函数?

标签 powershell start-job createthread

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

}

最佳答案

您需要创建一个 runspace并将其传递给 PowerShell 对象。检查此microsoft以正确方式使用运行空间的“教程”。 link还解释了如何使用运行空间池和脚本 block 参数。

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{
}

希望有帮助。

enter image description here

关于powershell - 为什么PowerShell创建的线程不能执行脚本函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56032373/

相关文章:

Powershell 作业内存消耗问题

Powershell:并行运行多个作业并查看来自后台作业的流式传输结果

c++ - 在类构造函数中将此指针传递给 CreateThread 在线程过程中表现得很奇怪

windows - shell32.dll : access violation during GetOpenFileName new thread

powershell - 将当前位置复制到剪贴板

windows - PowerShell:脚本不会计算自上次修改日期起超过 30 年的文件

windows - Jenkins 不会使用 Credential 参数运行 Start-Job

powershell - 通过Powershell将安全权限附加到文件夹

powershell - 通过 PowerShell 脚本 (.ps1) 上的快捷方式传递参数

c - 使用 WinAPI 线程的 Winsock 服务器重置第一个连接