【问题标题】:How to parse the output of the Windows command `wmic` using PowerShellHow to parse the output of the Windows command `wmic` using PowerShell
【发布时间】:2022-12-28 00:49:57
【问题描述】:

I am trying to parse the output of:

wmic copmutersystem

and

net.exe config workstation

using PowerShell to get an object as Key/Value pair and/or convert it to JSON String.

I know there is a PowerShell equivalent command:

Get-CimInstance  -Class Win32_computersystem

But the ask here is to figure out how to use PowerShell to parse a similar output for wmic CMD line.

【问题讨论】:

    标签: json powershell parsing wmi wmic


    【解决方案1】:

    Wmic can output csv or xml, but obviously get-wmiobject or get-ciminstance is preferred. You just need to find the class names instead of the aliases. The creator of wmic and powershell is the same.

    wmic computersystem list /format:csv | convertfrom-csv | select model
    
    Model
    -----
    OptiPlex 7490 AIO
    

    List wmic class aliases:

    wmic alias list brief
    wmic alias where "friendlyname = 'computersystem'" list brief
    

    For example:

    ComputerSystem                                   Select * from Win32_ComputerSystem
    
    get-ciminstance win32_computersystem
    

    【讨论】:

      【解决方案2】:

      Use the Get-CimInstance and ConvertTo-Json commandlets:

      Get-CimInstance -Class Win32_ComputerSystem | ConvertTo-Json
      

      Edit:Previous revision of this answer used Get-WMIObject, but that's been deprecated.

      【讨论】:

      • Dammit, I can only upvote this once!
      • Use Get-CimInstance -Class Win32_ComputerSystem instead.
      • According to github.com/PowerShell/PowerShell/issues/4766, I have to use this command instead Get-CimInstance -Class Win32_computersystem. Thank you. However, my intension of the question is how to parse a similar output if there is no equivalent command in PowerShell. I will update the question.
      • There will always be an equivalent command, if you figure out the true class name from the alias.
      • To elaborate on why Get-CimInstance is preferable: The CIM cmdlets (e.g., Get-CimInstance) superseded the WMI cmdlets (e.g., Get-WmiObject) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) v6+, where all future effort will go, doesn't evenhavethem anymore. Note that WMI stillunderliesthe CIM cmdlets, however. For more information, see this answer.
      猜你喜欢
      • 2022-11-20
      • 2022-12-01
      • 2022-12-02
      • 2022-12-02
      • 2022-12-02
      • 2022-12-19
      • 2022-12-15
      • 2022-12-01
      • 2022-12-01
      相关资源
      最近更新 更多