首页 > 解决方案 > 在 Powershell 中使用运行空间的网络视图

问题描述

我目前正在尝试启用一个脚本(它需要多台机器并列出每台机器上的共享)以使用运行空间与多个线程一起操作。我的共享查询是使用 NET VIEW 完成的,我的这部分代码完美地作为我现有脚本的一部分,它按顺序运行。

然而,当我扫描我的整个公司域时,并行查询是有意义的。在查看了一些 wiki 之后,我得到了下面的代码,但是这似乎可以执行并且只是挂起。我修改了代码,但没有明显的成功。我的小型机器样本在线,因为我事先进行了测试以验证这一点。

这是我第一次尝试运行空间,我真的不确定我哪里出错了,非常感谢您的帮助。

谢谢

$computers = @('computer1','computer2','computer3','computer4','computer5')
$pool = [RunspaceFactory]::CreateRunspacePool(1, 50)
$pool.ApartmentState = "MTA"
$pool.open()
$runspaces = @()  

$scriptblock = {
param([string]$m)

Write-Host $computers.Length
$pattern = [regex]"(.+)\s+(Disk)"
$shares_array  = New-Object System.Collections.ArrayList
$shares = net view $m | foreach {

if ($_ -match $pattern)
{
   $b = "\\$m\$($matches[1])"
   $shares_array.Add($b)

}
}}

ForEach($m in $computers) {
$runspace = [PowerShell]::Create()
$null = $runspace.AddScript($scriptblock)
$null = $runspace.AddArgument($m)
$runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
}

while ($runspaces.Status -ne $null)
{
$completed = $runspaces | Where-Object { $_.Status.IsCompleted -eq $true }
foreach ($runspace in $completed)
{
    $runspace.Pipe.EndInvoke($runspace.Status)
    $runspace.Status = $null
}
}

$pool.Close()
$pool.Dispose()

标签: powershellparallel-processingnetwork-programmingrunspace

解决方案


推荐阅读