Powershell Add-Member到对象(如果存在),否则为新对象

时间:2018-08-14 12:11:06

标签: powershell object

我试图更好地理解PowerShell,并且遇到了我的一个小项目中的一个问题。我想遍历性能计数器数组并获取CookedValue(例如:\ memory \ available MBs的Cooked值为4096,以显示4GB的可用内存)。

我希望我的输出采用JSON格式,如下所示:

PERFORMANCE
    MEMORY
       PAGE_FAULTS/SEC = 673
       %_COMMITED_MEMORY_IN_USE = 12
       AVAILABLE_MBYTES = 4096
       COMMITTED_BYTES = 3243
    PROCESS(*)
       %_PROCESSOR_TIME = 54
    LOGICALDISK(C:)
       DISK_READS/SEC = 462

这是下面我的脚本的当前状态。我正在努力地掌握对象管理,并且确实可以在正确的方向上进行微调。该脚本运行良好(它使用Get-Counter获取CookedValues,我可以打印结果),它只是以我遇到问题的逻辑方式将数据添加到对象中。

$CounterPathList = "\Memory\Page Faults/sec", "\Memory\% Committed Bytes In Use", "\Memory\Available MBytes", "\Memory\Committed Bytes", "\Process(*)\% Processor Time", "\LogicalDisk(C:)\Disk Reads/sec" 

$Performance = New-Object –TypeName PSObject

ForEach($CounterPath in $CounterPathList){

    $PathRoot = ($CounterPath.split('\')[1]).ToUpper()
    $Name = (($CounterPath -replace '.*\\') -replace " ","_").ToUpper()
    $Value=((Get-Counter($CounterPath)).countersamples | select -property cookedvalue).cookedvalue

    if(!($Performance | Where-Object -Property Name -eq $PathRoot)){
        Add-Member -InputObject $Performance -MemberType NoteProperty –Name $PathRoot –Value "" -force
    }else{
        Add-Member -InputObject $Performance.$PathRoot -MemberType NoteProperty –Name $Name –Value $Value -force
    }

}

$Performance | ConvertTo-JSON

上面的脚本当前输出:

$Performance | ConvertTo-JSON
{
    "MEMORY":  "",
    "PROCESS(*)":  "",
    "LOGICALDISK(C:)":  ""
}

1 个答案:

答案 0 :(得分:0)

恕我直言,PowerShell JSON cmdlet(dc1-ent.ent.ped.local Host name is )过于僵化-通常,它们与-lt 5.1一起使用时效果更好。 (有关一个示例,请参见本文结尾,另一个示例是V6 PSCustomObject添加了一个ConvertFrom-Json开关)这是一种使用简单的-AsHashtable来获取所需内容的方法:

Hashtable

请注意,代码段的最后一行已被注释掉。通过使用Although the documentation notes claim ConvertTo-Json is implemented JavaScriptSerializer class,当我运行cmdlet时,JSON将$counters = Get-Counter $wanted | select -ExpandProperty CounterSamples; $toJson = @{ 'PERFORMANCE' = @{}}; foreach ($c in $counters) { $computerName, $key, $subKey = $c.Path.Replace('\\', '') -split '\\'; $key = $key.ToUpper(); $subKey = ($subKey -replace '\s+', '_').ToUpper(); # each process has unique name => group by the common prefix if ($key -match '^process\(') { $subKey = $key; $key = 'PROCESS(*)'; } if (!$toJson.'PERFORMANCE'.ContainsKey($key)) { $toJson.'PERFORMANCE'.$key = @{}; } $toJson.'PERFORMANCE'.$key.$subKey = $c.CookedValue; } $serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer; $serializer.Serialize($toJson) | Out-File $outfile; # ConvertTo-JSON @($toJson) -Depth 10 | Out-File $outfile; 嵌套在Hashtable中。如果您关心空格/格式,则潜在的不利之处是array会将所有内容转储到单行字符串中。