在Powershell上运行并行线程

时间:2013-12-04 11:54:47

标签: multithreading powershell

我需要在应该并行运行的PS脚本上执行一些操作。使用PS作业不是一个真正的选择,因为必须被并行化的任务取决于在separete模块中定义的自定义函数。虽然我知道我可以使用 -InitializationScript 标志并导入包含我的自定义函数的模块,但我认为因为导入空洞模块而导致速度下降是“耗时”操作。

请记住我正在尝试在共享运行空间的单独线程中启动这些“任务”的所有事情。我的代码如下:

$ps = [Powershell]::Create().AddScript({ Get-CustomADDomain -dnsdomain $env: })
$threadRes = $ps.beginInvoke()
$ps.EndInvoke($threadRes)

这种方法的缺点是,由于我正在创建一个新的“powershell进程”,因此这个运行空间没有加载我的自定义模块,因此我遇到了与Jobs一样的情况。

如果我尝试使用以下代码将当前运行空间附加到新创建的$ ps:

$ps = [Powershell]::Create()
$ps.runspace = $host.runspace
$ps.AddScript({ Get-CustomADDomain -dnsdomain $env: })
$threadRes = $ps.beginInvoke()
$ps.EndInvoke($threadRes)

我收到错误,因为我正在尝试关闭当前的管道(坏事)。

我认为我的第二次拍摄是正确的,但我无法从调用脚本中检索结果,或者至少我无法看到这样做的方法。

很明显,我必须遗漏一些东西,所以你的任何建议都会非常有用!!!!

1 个答案:

答案 0 :(得分:0)

新作业或运行空间不会从导入当前会话的模块继承功能。话虽这么说,您不必导入整个模块。如果你在当前会话中有特定功能,你需要在作业中使用,你可以添加这样的功能:

function test_function {'This is a test'}
function test_function2 {'This is also a test'}

$job_functions = 'test_function','test_function2'

$init = [scriptblock]::Create(
 $(foreach ($job_function in $job_functions)
  { 
@"

function $job_function 
{$((get-item function:$job_function).definition)}

"@
  }))


$init

function test_function 
{'This is a test'}

function test_function2 
{'This is also a test'}