我正在编写一个脚本来检查大约 15 个远程服务器上的版本,但该脚本的执行时间比我预期的要长得多。
$listServers = @("compName1", "compName2", "compName3", ... "compName15")
"" | Out-File C:\temp\javaVersion.txt
"" | Out-File C:\temp\javaVersionLog.txt
$cred = Get-Credential
ForEach ($server in $listServers)
{
Measure-Command {$javaVersion = Invoke-Command -ComputerName $server -Credential $cred -Authentication Kerberos -ScriptBlock {Get-WmiObject -Class Win32_Product -Filter "Name like 'Java [0-9]%'" | Select -ExcludeProperty Version}} -ErrorAction SilentlyContinue -ErrorVariable errorOutput
$errorOutput | Out-File C:\temp\javaVersionLog.txt -Append
$server + $javaVersion | Out-File C:\temp\javaVersion.txt -Append
}
根据 Measure-Command 输出,这大约需要 21 秒才能完成。我是否有理由错过该脚本需要这么长时间才能完成?
Edit:
在被其他问题分散注意力后,我终于完成了剧本。
Start-Transcript C:\temp\javaVersion.txt
$listServers = @("compName1", "compName2", "compName3", ... "compName15")
$javaVersVerbose = ""
Invoke-Command -ComputerName $listServers -ScriptBlock {
$registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $_);
$javaKey = $registry.OpenSubKey('SOFTWARE\JavaSoft\Java Runtime Environment');
$javaVers = $javaKey.GetValue('CurrentVersion');
$javaVersVerbose = $javaKey.GetValue('Java' + $javaVers.Substring(2, 1) + 'FamilyVersion');
$nameKey = $registry.OpenSubKey('SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName');
$name = $nameKey.GetValue('ComputerName');
$name + " " + $javaVersVerbose | echo
} -ErrorAction SilentlyContinue -ErrorVariable errorOutput
$errorOutput | echo
Write-Host -NoNewLine 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho, IncludeKeyDown')
您不需要循环或串行执行此操作。invoke-command
需要收集ComputerName
s,并且可以并行运行请求。
$listServers = @("compName1", "compName2", "compName3", ... "compName15")
Invoke-Command -throttlelimit 4 -ComputerName $listServers -Credential $cred -Authentication Kerberos -ScriptBlock {Get-WmiObject -Class Win32_Product -Filter "Name like 'Java [0-9]%'" | Select -ExcludeProperty Version}} -ErrorAction SilentlyContinue -ErrorVariable errorOutput
然而,正如 Tim Ferrell 所指出的,您可以使用 Get-WMIObject 远程 ping 服务器,如果您将其作为一项作业来执行,它将并行运行多个请求。
Get-WMIObject Win32_Product -Filter "Name like 'Java [0-9]%'" -computername $listServers -throttlelimit 4 -asjob |select -excludeproperty version
然后使用 Job cmdlet 接收结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)