PowerShell快速获取Windows OS版本并执行不同的操作

问题描述

是否有更快的方法从服务器列表中获取特定的注册表值?我正在选择具有不同风格Windows的计算机的文本文件,并获取OS产品名称。我发现每台计算机要花几秒钟的时间。

当前脚本:

Clear-Host

# Prompt for file containing list of target
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$myDialog = New-Object System.Windows.Forms.OpenFileDialog
$myDialog.Title = "Select File of Target Systems"
$myDialog.InitialDirectory = $PSScriptRoot
$myDialog.Filter = "TXT (*.txt) | *.txt"
$result = $myDialog.ShowDialog()

If ($result -eq "OK") {
    $Computers = Get-Content $myDialog.FileName
}
Else {
    Write-Host "`nCancelled by User`n"
}

$Array = @()
  
# Loop Through Computers
ForEach ($Computer in $Computers) {
    Write-Warning "Processing $Computer"
       
    # Get Registry Values
    Try {      
        $Osversion = Invoke-Command -ComputerName $Computer -ScriptBlock { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName }
 
        # Create a custom object 
        $ComplexObject = New-Object PSCustomObject
        $ComplexObject | Add-Member -MemberType NoteProperty -Name "Server name" -Value $Computer
        $ComplexObject | Add-Member -MemberType NoteProperty -Name "OS Version" -Value $Osversion
 
        # Add custom object to our array
        $Array += $ComplexObject
    }
    Catch {
        $_.Exception.Message
        Break
    }

}
 
# Results
If ($Array) {
    # display results in new window
    $Array | Out-GridView -Title "OS Version Results"
 
    # display results in PS console
    $Array
}

我稍后在脚本中的最终目标是根据操作系统版本执行不同的操作,因此我想将它们分为独立的列表:

If (We have Win2008 servers) {
    "Do This"
}
If (We have Win2012R2 servers) {
    "Do This"
}

解决方法

Clear-Host

# Prompt for file containing list of target
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$myDialog = [System.Windows.Forms.OpenFileDialog]::new()
$myDialog.Title = "Select File of Target Systems"
$myDialog.InitialDirectory = $PSScriptRoot
$myDialog.Filter = "TXT (*.txt) | *.txt"
$result = $myDialog.ShowDialog()

If ($result -eq "OK") {
    $Computers = Get-Content $myDialog.FileName
}
Else {
    Write-Host "`nCancelled by User`n"
}

# Get Registry Values
$Array = Try {      
        Invoke-Command -ComputerName $Computers -ScriptBlock {
            (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
    } -ErrorAction stop | Select-Object @{n="Server Name";e={$_.pscomputername}},@{n="OS Version";e={$_}}
}
Catch {
    write-warning $_.Exception.Message
    break
}

# Results
If ($Array) {
    # Display results in new window
    $Array | Out-GridView -Title "OS Version Results"

    # Display results in PS console
    $Array
}
,

您可以像使用std::string

Get-AdComputer