Powershell - 如何用String替换OS版本号

时间:2016-06-24 14:07:36

标签: powershell if-statement

我正在查询远程服务器的操作系统。我知道我可以返回版本,但我想用友好名称替换这些值。我到目前为止的代码是:

$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"} 

但这似乎不起作用,只能回归" 2003"而不管。请帮助,我对PS和编码很新。

感谢

3 个答案:

答案 0 :(得分:4)

问题在于您的if声明。将布尔表达式放在squiggly括号内使它成为一个脚本块,并且在被转换为布尔值之前将被转换为字符串。施放给布尔人的字符串总是评估为真,除非它们是空的。

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"') [...]

这总是如此。

尝试:

$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。但是,我没有足够的信息来了解您实际尝试使用脚本执行的操作(例如您使用$Build执行的操作)以便能够解决此问题。

答案 1 :(得分:3)

我最初这么说,但我已经改变了主意

这只返回2003的原因是您只在列表中的单个条目上运行If代码。

<强>错误

正如TessellatingHeckler所说,你的if不工作的原因是你有太多花括号,所以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

答案 2 :(得分:1)

您可以使用:

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

此外,您可以看到此WMI对象所包含的所有内容:

Get-WmiObject -Class Win32_OperatingSystem | fl *

编辑:如果要从字符串中删除某些文字,可以使用-replace

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