【问题标题】:Powershell GWMI win32_operatingsystem trim outputPowershell GWMI win32_operatingsystem 修剪输出
【发布时间】:2015-02-03 01:34:58
【问题描述】:

当你使用

(GWMI -ComputerName $server -Class Win32_OperatingSystem -ErrorAction Stop).Caption

得到类似的标题

Microsoft(R) Windows(R) Server 2003 Standard x64 Edition
Microsoft Windows Server 2008 R2 Standard
Microsoft Windows Server 2012 Datacenter

从结果中删除"Microsoft Windows""Microsoft(R) Windows" 的简单方法是什么?

我想出了:

(GWMI Win32_OperatingSystem -Comp $server).Caption -Replace "^Microsoft Windows "

这会将"Microsoft Windows Server 2012 Datacenter" 变成"Server 2012 Datacenter",但是 2003 和 2008 年的旧机器不匹配替换正则表达式。

【问题讨论】:

    标签: regex powershell scripting


    【解决方案1】:

    这是我的

    PS > gwmi Win32_OperatingSystem | % Caption
    Microsoft Windows 7 Ultimate
    

    你想要什么

    PS > gwmi Win32_OperatingSystem | % Caption | % split ' ' 3 | select -last 1
    7 Ultimate
    

    【讨论】:

    • 现在看起来太容易了!谢谢! - 编辑,我似乎无法发布我得到的修改后的代码,但这是一个衬里:$result.OS = (GWMI -ComputerName $server -Class Win32_OperatingSystem -ErrorAction Stop).Caption | % split | select -Skip 2 | & {"$input" }
    【解决方案2】:

    我在我的环境中找到了所有操作系统作为测试。我不会担心这个答案的 WMI,因为这不是问题的重点。

    使用以下包含我所有测试示例的此处字符串

    $OSes = @"
    Microsoft Windows 7 Professional
    Microsoft Windows 8.1 Pro
    Microsoft Windows Server 2008 R2 Datacenter
    Microsoft Windows Server 2008 R2 Enterprise
    Microsoft Windows Server 2008 R2 Standard
    Microsoft Windows Storage Server 2008 R2 Standard
    Microsoft Windows XP Professional
    Microsoft(R) Windows(R) Server 2003, Standard Edition
    Microsoft® Windows Server® 2008 Standard
    "@.Split("`r`n")
    

    我运行一个正则表达式,它使用可选的 (R) 和 ®(

    $OSes -replace "Microsoft(\(R\)|®)?\sWindows(\(R\))?\s"
    

    更多关于正则表达式的详细信息可以找到here

    净输出

    7 Professional
    8.1 Pro
    Server 2008 R2 Datacenter
    Server 2008 R2 Enterprise
    Server 2008 R2 Standard
    Storage Server 2008 R2 Standard
    XP Professional
    Server 2003, Standard Edition
    Server® 2008 Standard
    

    【讨论】:

    • 也谢谢你,这是在行动:$result.OS = (GWMI -ComputerName $server -Class Win32_OperatingSystem -ErrorAction Stop).Caption -replace "Microsoft(\(R\)|®)?\sWindows(\(R\))?\s"
    【解决方案3】:

    我将继续使用正则表达式方法并使用“Microsoft {可选地后跟 (R)}”,如下例所示:

    $s = @(   'Microsoft(R) Windows(R) Server 2003 Standard x64 Edition'
            , 'Microsoft Windows Server 2008 R2 Standard'
            , 'Microsoft Windows Server 2012 Datacenter'
        )
    
    write "`n`n"
    
    $s | % { $_ -replace "Microsoft(\(R\)|) Windows(\(R\)|) " }
    

    【讨论】:

    • @Matt:是的! (我可能只是在您查看它时才看到它,因为您的编辑将它撞到了首页的顶部)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2014-08-09
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多