2017-10-04 54 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