[英]Powershell for JSON
I made this script in powershell to collect some information from the computer and I need to export to JSON format with some specifications 我在Powershell中制作了此脚本,以从计算机中收集一些信息,我需要导出为具有某些规范的JSON格式
$osinfo = Get-WmiObject Win32_OperatingSystem -ErrorAction STOP |
Select-Object @{Name='computername';Expression={$_.CSName}};
Write-Host "Computer_INfo:"
$osinfo | ConvertTo-Json
$rede = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ErrorAction STOP | where-object -FilterScript {$_.IPEnabled -eq $true} | Select-Object @{Name='Description';Expression={$_.Description}},
@{Name='IP_Address';Expression={$_.IPAddress[0]}};
Write-Host "LAN_INfo:"
$rede | ConvertTo-Json
The result of this command generates this JSON 该命令的结果生成此JSON
Computer_INfo:
{
"computername": "DESKTOP-PCJTTEG"
}
LAN_INfo:
[
{
"Description": "Hyper-V Virtual Ethernet Adapter",
"IP_Address": "192.168.65.241"
},
{
"Description": "Hyper-V Virtual Ethernet Adapter #2",
"IP_Address": "192.168.10.104"
}
]
I wanted it to be this way. 我希望这样。
{Computer_Info:
[
{
"computername": "DESKTOP-PCJTTEG"
}
]
},LAN_INfo:{
[
{
"Description": "Hyper-V Virtual Ethernet Adapter",
"IP_Address": "192.168.65.241"
},
{
"Description": "Hyper-V Virtual Ethernet Adapter #2",
"IP_Address": "192.168.10.104" }
]
}
You can define the structure for your Json by designing your PSCustomObject in the way you desire. 您可以通过以所需的方式设计PSCustomObject来定义Json的结构。 To have arrays, even if you have 1 element, add the
@()
array constructor. 要拥有数组,即使您只有1个元素,也要添加
@()
数组构造函数。 When converted to json, il will transpose to your missing []
转换为json时,il将转置为您缺少的
[]
Default depth when converting to Json is 4, which can be adjusted up to 100 layers. 转换为Json时的默认深度为4,最多可以调整100层。 In the case of your output, I adjusted it to avoid missing some content in the final output.
对于您的输出,我对其进行了调整,以避免在最终输出中丢失某些内容。
Here's your code, with the rendered output you were looking for. 这是您的代码,以及您正在寻找的渲染输出。
$osinfo = Get-WmiObject Win32_OperatingSystem -ErrorAction STOP |
Select-Object @{Name = 'computername'; Expression = { $_.CSName } };
$rede = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ErrorAction STOP | where-object -FilterScript { $_.IPEnabled -eq $true } |
Select-Object @{Name = 'Description'; Expression = { $_.Description } },
@{Name = 'IP_Address'; Expression = { $_.IPAddress[0] } };
[PSCustomObject]@{
Computer_Info = @(
$osinfo,
@{'LAN_INfo' = $rede }
)
} | ConvertTo-Json -Depth 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.