I am executing:
systeminfo | ConvertTo-Json
"Host Name: namehere",
"OS Name: Microsoft Windows 10 Enterprise",
...
but I need
"Host Name": "namehere",
"OS Name": "Microsoft Windows 10 Enterprise",
...
The following command gives a similar issue
systeminfo | ConvertTo-Xml -As String
<?xml version="1.0" encoding="utf-8"?>
<Objects>
<Object Type="System.String"></Object>
<Object Type="System.String">Host Name: namehere</Object>
<Object Type="System.String">OS Name: Microsoft Windows 10 Enterprise</Object> "
but I need something like:
<?xml version="1.0" encoding="utf-8"?>
<HostName>namehere</HostName>
<OSName>Microsoft Windows 10 Enterprise</OSName>
...
try this:
systeminfo /fo CSV | ConvertFrom-Csv
or
systeminfo /fo CSV | ConvertFrom-Csv | convertto-json
To complement thom schumacher's helpful answer :
In PSv5+ you can alternatively use Get-ComputerInfo
.
While the field (property) names in the resulting [Microsoft.PowerShell.Commands.ComputerInfo]
instance aren't identical to the ones in systeminfo
's output, you're likely to get additional information there.
Since Get-ComputerInfo
outputs an object whose properties contain the information, you can send that directly to ConvertTo-Json
/ ConvertTo-Xml
Get-ComputerInfo | ConvertTo-Json
As for what you tried :
External programs such as systeminfo
can only output text , and often do so in (semi-) unstructured form that is more geared toward human viewing than further programmatic processing.
By contrast, in order to get meaningful output from ConvertTo-Json
/ ConvertTo-Xml
, you need either a structured text format - which systeminfo
happens to offer via its /FO
option - or input objects , which is what you get PowerShell's cmdlets output.
Therefore, it's usually better to look for PowerShell alternatives to external programs; if their are none, and if the external programs don't offer structured-text output, you have to resort to doing your own text-parsing in order to impose structure, which can be both brittle and cumbersome.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.