Powershell - how to replace OS version number with String

I am requesting remote servers for my operating system. I know that I can return the Version, but I want to replace these values ​​with a friendly name. The code I have so far is:

$Computer = (gc c:\servers.txt)
$BuildVersion = Get-WmiObject -Class Win32_OperatingSystem -Property Version, CSName -ComputerName $Computer -ErrorAction SilentlyContinue
$Build=$BuildVersion.version
   If ({$BuildVersion.Version -match "5.2.3790"}) 
          {$Build="2003"}
   Elseif ({$BuildVersion.Version -match "6.1.7601"}) 
           {$Build="2008"}
   Elseif ({$BuildVersion.Version -like "6.3.9600"}) 
          {$Build="2012"} 

But this does not seem to work and only returns “2003”. Please help, I'm pretty new to PS and coding.

thank

+4
source share
3 answers

You can use this:

Get-WmiObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption

In addition, you can see everything that this WMI object runs as follows:

Get-WmiObject -Class Win32_OperatingSystem | fl *

Edit: if you want to remove text from a line, you can use -replace:

(Get-WmiObject -Class Win32_OperatingSystem |
    Select-Object -ExpandProperty Caption) -replace "Microsoft Windows Server ",""
+1
source

if. script, , . , , , .

PS C:\> {$BuildVersion.Version -match "5.2.3790"}
$BuildVersion.Version -match "5.2.3790"
PS C:\> ({$BuildVersion.Version -match "5.2.3790"}) -as [bool]
True
PS C:\> $BuildVersion.Version -match "5.2.3790"
False
PS C:\> ($BuildVersion.Version -match "5.2.3790") -as [bool]
False

, , :

if ([bool]'$BuildVersion.Version -match "5.2.3790"') [...]

.

Try:

$Computer = (gc c:\servers.txt)
$BuildVersion = Get-WmiObject -Class Win32_OperatingSystem -Property Version, CSName -ComputerName $Computer -ErrorAction SilentlyContinue
$Build=$BuildVersion.version
If ($BuildVersion.Version -match "5.2.3790") 
{
    $Build = "2003"
}
Elseif ($BuildVersion.Version -match "6.1.7601") 
{
    $Build = "2008"
}
Elseif ($BuildVersion.Version -like "6.3.9600") 
{
    $Build = "2012"
}

, , , .

. $BuildVersion, , . $BuildVersion. , , script (, $Build), .

+4

, .

, 2003, , If .

Wrong

TessellatingHeckler, , , , , PowerShell .

, , . , ForEach. If {} Switch, , , , , . .

, , , , , .

$Computer = (gc c:\servers.txt)
ForEach ($system in $computer){
    $BuildVersion = Get-WmiObject -Class Win32_OperatingSystem -Property Version, CSName -ComputerName $system -ErrorAction SilentlyContinue 
    $Build=$BuildVersion.version

    switch ($build){
        "5.2.3790" {$Build="2003"}
        "6.1.7601" {$Build="2008"}
        "6.3.9600" {$Build="2012"}

    }

    #output results
    [pscustomobject]@{Server=$system;OSVersion=$build;CSName=$buildVersion.CSname}        
}#EndOfForEach

>Server   OSVersion CSName  
------   --------- ------  
dc2012   2012      DC2012  
sccm1511 2012      SCCM1511
+3

All Articles