优化Powershell脚本以查询远程服务器操作系统版本



我想优化一个简单的任务:将服务器操作系统版本拉到一个整洁的表中。但是,我们环境中的一些服务器禁用了Powershell。下面你可以找到我的剧本,它很管用!但是,每台服务器大约需要20秒左右的时间,因为它会等待服务器返回调用命令的结果,然后再转到列表中的下一台服务器。我知道有一种方法可以异步地从PS命令中提取结果,但当我需要为无法处理PS的服务器使用cmd行语法时,这可能吗,如catch语句所示?

$referencefile = "ps_servers_to_query.csv"
$export_location = "ps_server_os_export.csv"
$Array = @()
$servers = get-content $referencefile
foreach ($server in $servers){
#attempt to query the server with Powershell. 
try{

$os_version = invoke-command -ComputerName $server -ScriptBlock {Get-ComputerInfo -Property WindowsProductName} -ErrorAction stop
$os_version = $os_version.WindowsProductName
} # If server doesnt have PS installed/or is disabled, then we will resort to CMD Prompt, this takes longer however.. also we will need to convert a string to an object.  
catch {
$os_version = invoke-command -ComputerName $server -ScriptBlock {systeminfo | find "OS Name:"} # this returns a string that represents the datetime of reboot
$os_version = $os_version.replace('OS Name: ', '') # Remove the leading text
$os_version = $os_version.replace('  ','') # Remove leading spaces 
$os_version = $os_version.replace('Microsoft ','') # Removes Microsoft for data standardization 
}  
# Output each iteration of the loop into an array
$Row = "" | Select ServerName, OSVersion
$Row.ServerName = $Server
$Row.OSVersion = $os_version
$Array += $Row
}
# Export results to csv. 
$Array | Export-Csv -Path $export_location -Force 

编辑:这是我想要完成的。一次将命令发送到所有服务器(少于30个(,并让它们同时处理命令,而不是逐个处理。我知道如果他们都能接受PowerShell命令,我就能做到这一点,但由于他们不能,我很挣扎。此脚本总共运行大约需要6分钟。

提前谢谢!

如果我做对了,你只需要这样的东西:

$referencefile = "ps_servers_to_query.csv"
$export_location = "ps_server_os_export.csv"
$ComputerName = Get-Content -Path $referencefile
$Result = 
Get-CimInstance -ClassName CIM_OperatingSystem -ComputerName $ComputerName | 
Select-Object -Property Caption,PSComputerName
$Result 
| Export-Csv -Path $export_location -NoTypeInformation

最新更新