在Powershell中创建动态哈希表

时间:2018-08-07 09:59:23

标签: powershell arraylist dynamic hashtable

我想在Powershell中创建本地计算机的概述,并通过哈希表以JSON输出。现在它可以有几个硬盘,并且必须在哈希表中动态创建。

我的代码:

$name = (Get-WmiObject -Class Win32_ComputerSystem -Property
Name).Name     @{foreach ($Disk in $Disk) { $stats.Add("$platten", $Disk[0].VolumeName) }

       stats = @{ $name= @{
                 CPUusage = $CPU
                 RAMusage = $ram
                 disknames = $disknames[1]
                 SSDsum = $ssdsum
                 HDDsum = $hddsum
                 Disksum = $disksum
              }
              $disk1 = @{

              }

              $disk2 = @{

              }

              $disk3 = @{

              }
            }}    

现在,我询问硬盘驱动器并将其保存在哈希表中。然后foreach循环应遍历每个磁盘,然后将数据输入另一个哈希表。

这是错误,我尝试将其放入哈希表中,但它不起作用。

2 个答案:

答案 0 :(得分:0)

如果您创建哈希表,则哈希表通常具有固定大小

像这样初始化变量$disknames

$disknames = New-Object System.Collections.ArrayList

然后,您可以添加尝试输入的内容

答案 1 :(得分:0)

您的问题非常不清楚,结尾不完整。但是,我认为这可能会对您有所帮助:

$ComuterSystem = Get-CimInstance -ClassName Win32_ComputerSystem  

$Result = foreach ($Computer in $ComuterSystem) {
    $LogicalDisk = Get-CimInstance -ClassName win32_logicaldisk -ComputerName $ComuterSystem.Name

    # Create a new hashtable for each computer
    $diskHash = @{}

    # Foreach disk of that computer add it to the hashtable
    foreach ($disk in ($LogicalDisk.Where({$_.DeviceID}))) {
        $diskHash.Add($disk.DeviceID, $disk.Size)
    }

    [PSCustomObject]@{
        Name = $Computer.Name
        Model = $Computer.Model
        Manufacturer = $Computer.Manufacturer
        # Easiest is to simply store all data:
        LogicalDisk = $LogicalDisk
        # Or store the hashtable with your key value pair
        Disks = $diskHash
        # Or store a selection of what you need
        Selection = $LogicalDisk | Select-Object DeviceID, VolumeName, Size, FreeSpace
    }
}

$Result

$Result.Disks

$Result.LogicalDisk

$Result.Selection