Powershell使用多个函数创建新对象

时间:2012-06-20 03:44:56

标签: arrays object powershell

所以我几乎已经解决了我的初始问题,但我在这里碰到了一堵砖墙:我有一组需要格式化成表格的3个变量(最终会变得更多)。我已经为每个变量创建了函数,我可以使用以下代码成功组合两个变量:

$pids = get-counter -listset process | get-counter -maxsamples 1 | select -expandproperty countersamples | where {$_.path -like "*\id process" -and $_.path -like $filter} | select cookedvalue | ForEach {$_.cookedvalue}
function GetMemoryUsage  { ...code here... }
function GetAppID { ...code here.... }
$combined = $pids | %{ $wapp = GetAppID $_
             $obj = new-object psobject
             $obj | add-member -name WP -type noteproperty -value $wapp
             $obj | add-member -name "Process ID" -type noteproperty -value $_
             $obj
        }
Write-Output $combined

我的问题是:如何在此处添加GetMemoryUsage作为对象?我尝试过使用一个函数,但它不是很好。请注意,我不想在这里使用哈希表,因为我相信他们只在v2中运行,而且我仍然有机器运行v1。谢谢!

2 个答案:

答案 0 :(得分:0)

如果您正在使用进程ID和内存消耗,那么这应该适合您:

Get-Process | Select Name,ID,WorkingSet

答案 1 :(得分:0)

想出来了!

这里的关键是成功地将它输出到数组。我在这里遇到了很多弊端,但你必须通过他们工作。

$pids = get-counter -listset process | get-counter -maxsamples 1 | select -expandproperty countersamples | where {$_.path -like "*\id process" -and $_.path -like $filter} | select cookedvalue | ForEach {$_.cookedvalue}
function GetMemoryUsage  { ...code here... }
function GetAppID { ...code here.... }
$myresults = @()
$x = foreach ($ids in $pids) {
         $thisapp = GetAppID $ids
         $thismem = GetMemoryUsage $ids
         $robj = New-Object System.Object
     $robj | Add-Member -type NoteProperty -name WP -value $thisapp
     $robj | Add-Member -type NoteProperty -name Memory -value $thismem
     $robj | Add-Member -type NoteProperty -name Process -value $ids
     $myresults += $robj
}
$myresults | ft -auto

这种方法的好处在于你可以输入无数个变量,只要你能将这些变量与数组联系起来,那么你就可以了。