Powershell GWMI win32_operatingsystem修剪输出

时间:2014-12-04 23:54:20

标签: regex powershell scripting

使用时

(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年的旧计算机与替换正则表达式不匹配。

3 个答案:

答案 0 :(得分:4)

这是我的

PS > gwmi Win32_OperatingSystem | % Caption
Microsoft Windows 7 Ultimate

以及你想要的东西

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

答案 1 :(得分:3)

我发现环境中的所有操作系统都是测试。我不会为这个答案担心WMI,因为这不是问题的焦点。

使用以下here-string包含我的所有测试示例

$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)和®(< - 版权符号)的Microsoft Windows

$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

答案 2 :(得分:1)

我会继续使用正则表达式方法,然后选择' 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\)|) " }
相关问题