简体   繁体   English

Powershell多线程无法在cmd.exe上运行

[英]Powershell multithreading not working on cmd.exe

I need to run some code in powershell using multi-thread, i have tested a simple snippet and it runs fine on a powershell console. 我需要使用多线程在powershell中运行一些代码,我已经测试了一个简单的代码段,并且在powershell控制台上运行良好。 however when i try to run on a cmd.exe the code doesnt execute and no error was thrown wondering what is going on? 但是,当我尝试在cmd.exe上运行时,代码没有执行,并且没有任何错误,想知道这是怎么回事? if someone you help on this. 如果有人帮助您。

sample code as follow 示例代码如下

$throttleLimit = 10

$iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $iss, $Host)
$Pool.Open()

$ScriptBlock = {
param($id)
Start-Sleep -Seconds 2
Write-Host "Done processing ID $id"
[System.Console]::WriteLine("Done processing ID $id")
}

for ($x = 1; $x -le 40; $x++) {
$powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($x)
$powershell.RunspacePool = $Pool
$handle = $powershell.BeginInvoke()
}

my batch file code is as follow 我的批处理文件代码如下

powershell -Command .\multiT.ps1 2>&1

In the ISE, the script finishes before the output from the threads starts to show up. 在ISE中,脚本会在线程输出开始显示之前完成。 I added start-sleep -sec 10 to the end of the code and I get output from cmd now. 我在代码的末尾添加了start-sleep -sec 10 ,现在我从cmd获得输出。 For some reason the output is doubled, though (as in, I get 2 lines for each thread). 由于某种原因,输出却翻了一番(例如,每个线程有2行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM