【发布时间】:2018-02-26 21:03:50
【问题描述】:
我目前有一个 powershell (v2) 脚本,它获取主机 PC 列表,远程检查某些文件/软件是否在它们应该在的位置,并在完成后通过电子邮件发送一串结果。但是,当尝试在 100 多个房间上依次执行此操作时,脚本需要很长时间才能完成。
为了加快速度,我一直在尝试通过使用作业来报告每个主机名来使脚本成为多线程。为了清楚起见,我已将代码的主要部分放在下面,删除了一些较大的不相关部分。
$pcHostNames = Get-Content "$scriptPath\HostNames.txt"
$scriptBlock = {
Param(pcHostName)
$softwareInstalled = $false
# Test to see if host can be reached
If (Test-Connection -ComputerName $pcHostName -Quiet)
{
# Multiple lines of code to check if different files/software are installed on each remote PC
# If they are installed, set $softwareInstalled to true
if (-not $softwareInstalled)
{
$reportList += "$pcHostName`: Not installed`n"
}
else
{
$reportList += "$pcHostName`: Fully installed`n"
}
}
else
{
$reportList += "$pcHostName`: Error - Connection failed`n"
}
} # End - $scriptBlock
$pcHostNames | % { Start-Job -Scriptblock $scriptBlock -ArgumentList $_ } | Get-Job | Wait-Job | Receive-Job
当前脚本 ping PC,然后检查是否安装了各种文件/软件,并向 $reportList 添加一个字符串,然后在电子邮件中使用该字符串在我的代码的另一部分发送报告。
由于 $reportList 超出了每项工作的范围,我得到的只是脚本末尾的空白电子邮件。由于无法从作业中将字符串值添加到变量中,有没有办法编辑作业管道的代码以返回字符串值,然后我可以将其添加到变量中?
我认为这个问题可能与我的代码的最后一行有关,因此我尝试了几种不同的执行作业的变体,但对我在网上找到的内容不太走运。
或者,有没有更好的方法通过另一种方法来多线程这个脚本?
【问题讨论】:
标签: powershell powershell-2.0 jobs