将在foreach循环中创建的属性发送到PSCustomObject

时间:2016-01-24 01:10:11

标签: powershell

我想读出一些在网络服务器上运行的进程的信息。我坚持把我的信息变成一个变量并将其导出到一个日志文件

如何将$ProcessData放入 $sig = @' [DllImport("User32.dll")] public static extern int GetGuiResources(IntPtr hProcess, int uiFlags); '@ Add-Type -MemberDefinition $sig -name NativeMethods -namespace Win32 $processes = [System.Diagnostics.Process]::GetProcesses() [int]$gdiHandleCount = 0 $ProcessData = New-Object PSCustomObject ForEach ($p in $processes) { try{ $gdiHandles = [Win32.NativeMethods]::GetGuiResources($p.Handle, 0) $gdiHandleCount += $gdiHandles $properties = @{ 'ProcessName'=$p.name; 'CPU'=$p.cpu; 'Handles'=$p.Handles; 'GDI-Objects'=$gdiHandles.ToString } } catch { #"Error accessing " + $p.Name } } PSCustom对象?

主要目标是获取在我的服务器上运行的每个进程的gdi句柄。

var first = {
  loginRememberMe: false,
  test: false
}

var second = [{
  Objectname: "loginEmail",
  value: "one"
}, {
  Objectname: "loginPassword",
  value: "two"
}]

var modifiedArray = addObjectKeysToArray(second, first);

console.log( modifiedArray );
console.log( second );
console.assert(second !== modifiedArray, 'both arrays should be different');

function addObjectKeysToArray(arr, obj) {
  // copy the arr so we don't modify the original
  var arrCopy = arr.slice(0);
  // loop through the object properties
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      // add to the copied array
      arrCopy.push({
        Objectname: key,
        value: obj[key]
      });
    }
  }
  return arrCopy;
}

谢谢!

2 个答案:

答案 0 :(得分:2)

看起来您只想将GDI对象添加到流程信息中。请使用calculated property

$processes = [Diagnostics.Process]::GetProcesses() |
             Select-Object Name, Cpu, Handles, @{n='GDI-Objects';e={
               [Win32.NativeMethods]::GetGuiResources($_.Handle, 0).ToString()
             }}

答案 1 :(得分:0)

$ProcessData = New-Object PSCustomObject -Property @{
    'ProcessName'=$p.name;
    'CPU'=$p.cpu;
    'Handles'=$p.Handles;
    'GDI-Objects'=$gdiHandles.ToString
}

OR

$Properties = @{
    'ProcessName'=$p.name;
    'CPU'=$p.cpu;
    'Handles'=$p.Handles;
    'GDI-Objects'=$gdiHandles.ToString
}
$ProcessData = New-Object PSCustomObject -Property $Properties

我通常选择A