2017-10-04 50 views
1

因此,我已经制作了此脚本,可以找到机器上安装的所有软件版本,并让人们知道哪些软件以及何时安装在多个VM上。以特定的方式从Powershell序列化JSON

我想把它放在我们使用的仪表板提供程序上,但它们有一个特定的格式来使用它。

它确实会生成一个有效的JSON,但我只是发现它不符合公司希望的格式。

具体做法是:

{"table": [["header1", "header2"], ["row1column1", "row1column2"], ["row2column1", "row2column2"]]} 

我首先想到的是产生一个标题行作为开始变量,然后各个变量的每个组件,但那种感觉非常繁琐和费力的为每个单独的行创建变量的数据(日期,软件名称等)。然后在最后它们合并为1,并转换为JSON

我的脚本是这样的:

[CmdletBinding()] 
Param (
    [Parameter(ValueFromPipeline = $true, 
     ValueFromPipelinebyPropertyName = $true)] 
    [Alias("Servers")] 
    [string[]]$Name = (Get-Content "c:\utils\servers.txt") 
) 
Begin { 

} 
Process { 
    $AllComputers = @() 
    #Gather all computer names before processing 
    ForEach ($Computer in $Name) { 
     $AllComputers += $Computer 
    } 
} 

End { 
    ForEach ($Computer in $AllComputers) { 

     write-output "Checking $computer" 
     if ($computer -like "*x86*") { 
      $data = Invoke-Command -cn $computer -ScriptBlock {Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object @{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate | Where-object { $_.Publisher -match "Foobar" }} 
      $jsondata += $data 
     } 
     else { 
      $data = Invoke-Command -cn $computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object @{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate | Where-object { $_.Publisher -match "foobar" } } 
      $jsondata += $data 
     } 
    } 
    $jsondata | ConvertTo-Json -depth 100 | Out-File "\\servername\C$\Utils\InstalledApps.json" 
} 
+0

“{”table“:[[”header1“,”header2“]'部分需要逐字还是只需要遵循该格式?所有参赛作品最终都会放在一张桌子上? – Matt

+0

不幸它是必需的。 Header1 Header2可以是任何值,但必须包含表格 – Ericrs

回答

0

从提供我断定你正在寻找数组的数组样本输出格式。有一个"bug" using ConvertTo-Json when trying to do this,但是因为我们无论如何都需要它在一个表格对象中。我将使用您的代码显示一个示例,但仅显示在本地计算机上。将它集成到代码中不应该是一个问题。

# gather the results 
$results = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-object { $_.Publisher -match "The" } | Select-Object @{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate 

# Prepare an array of arrays for the output. 
$outputToBeConverted = @() 

# build the header 
$header = ($results | Get-Member -MemberType NoteProperty).Name 
$outputToBeConverted += ,$header 

# Add the rows 
Foreach($item in $results){ 
    # Create a string array by calling each property individually 
    $outputToBeConverted += ,[string[]]($header | ForEach-Object{$item."$_"}) 
} 

[pscustomobject]@{table=$outputToBeConverted} | ConvertTo-Json -Depth 5 

基本上它是使阵列的锯齿形阵列,其中所述第一构件是你的“标头”和每行从$results集合中的项目手动构建的。

您将看到上面使用的一元运算符,。这是为了防止PowerShell展开数组。没有这些,你可能会在输出中产生一个长阵列。

+0

谢谢我会试试这个! – Ericrs