【发布时间】:2015-11-10 16:41:12
【问题描述】:
我正在尝试创建一个 Web API,它将 PowerShell 命令的输出转换为 JSON。是否有可以执行此操作或将 PSObject 转换为 JSON 的库?
PSObject 属性根据生成它的命令而变化。我尝试将 PSObject 传递给“ConvertTo-Json”,但我得到了额外的对象信息。
PowerShell 命令:
Get-Process | Select -Property Handles,ProcessName | ConvertTo-Json
JsonConvert.SerializeObject()之后的输出:
"{\"CliXml\":\"<Objs Version=\\\"1.1.0.1\\\" xmlns=\\\"http://schemas.microsoft.com/powershell/2004/04\\\">\\r\\n <Obj RefId=\\\"0\\\">\\r\\n<TN RefId=\\\"0\\\">\\r\\n <T>System.String</T>\\r\\n <T>System.Object</T>\\r\\n </TN>\\r\\n <ToString>[_x000D__x000A_ {_x000D__x000A_\\\"Handles\\\":163,_x000D__x000A_\\\"ProcessName\\\":\\\"AppleMobileDeviceService\\\"_x000D__x000A_},_x000D__x000A_ {_x000D__x000A_\\\"Handles\\\": 972,_x000D__x000A_\\\"ProcessName\\\":\\\"CcmExec\\\"_x000D__x000A_},_x000D__x000A_{_x000D__x000A_\\\"Handles\\\": 1838,_x000D__x000A_\\\"ProcessName\\\":\\\"ccSvcHst\\\"_x000D__x000A_}"
用于 BeginInvoke 的 PowerShell 命令。
PowerShell 命令:
Get-Process | Select -Property Handles,ProcessName
JsonConvert.SerializeObject(PSObj)之后的输出:
"[{\"CliXml\":\"<Objs Version=\\\"1.1.0.1\\\" xmlns=\\\"http://schemas.microsoft.com/powershell/2004/04\\\">\\r\\n <Obj RefId=\\\"0\\\">\\r\\n <TN RefId=\\\"0\\\">\\r\\n <T>Selected.System.Diagnostics.Process</T>\\r\\n <T>System.Management.Automation.PSCustomObject</T>\\r\\n <T>System.Object</T>\\r\\n </TN>\\r\\n <ToString>@{Handles=163; ProcessName=AppleMobileDeviceService}</ToString>\\r\\n <Obj RefId=\\\"1\\\">\\r\\n <TNRef RefId=\\\"0\\\" />\\r\\n <MS>\\r\\n <I32 N=\\\"Handles\\\">163</I32>\\r\\n <S N=\\\"ProcessName\\\">AppleMobileDeviceService</S></Objs>\"}}]
【问题讨论】:
-
ConvertTo-JSON听起来正是您所追求的......额外的属性是什么?如果要删除属性,可以使用 select-object 在转换为 json 之前仅指定要使用的属性。 -
那没有用数据更新帖子。
-
Convert-Json 在我看来不是一个好的解决方案,因为它将枚举转换为它们的序数值。看到这个答案stackoverflow.com/questions/44494409/…
标签: c# json powershell