如何合并powershell脚本以在一个csv文件中获取磁盘使用空间,磁盘可用空间,CPU利用率和内存利用率?

时间:2017-09-13 20:06:32

标签: powershell

我有一个单独的代码来获取磁盘空间的详细信息,我如何合并这两个程序来获取磁盘使用率,磁盘空闲空间和CPU利用率,这样我就可以在一个csv文件中获得所有输出。

    Get-WmiObject -Class Win32_LogicalDisk -ComputerName "PhatuggiKaDabba" | 
Where-Object {$_.DriveType -eq 3} |
Select-Object DeviceID, Description,`
    @{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
    @{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}} |
    Export-CSV 'D:\code\DiskSpaceUsage .csv' -noType

我还有一个用powershell编写的文件,它提供CPU利用率,内存使用率和用户

    GC D:\ServerList.txt | % {
$Comp = $_
If (Test-Connection $Comp -Quiet){
$Luser = (Get-WmiObject -class win32_process -Filter "Name='Explorer.exe'" -ComputerName $Comp |
% {$_.GetOwner().User} | Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
      New-Object PSObject -Property @{
      Server = $Comp
      "CPU usage" = "$((GWMI -ComputerName $COMP win32_processor | Measure-Object -property LoadPercentage -Average).Average) %"
      "Memory usage" = "$("{0:N2}" -f ((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/ $Mem.TotalVisibleMemorySize)) %"
      "Total FreeSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" | Measure-Object -property FreeSpace -Sum).Sum /1GB)) GB"
      "logged Users" = $Luser
      }
}
Else{
"" | Select @{N="Server";E={$Comp}},"CPU usage","Memory usage","Total FreeSpace","logged Users"
}
}| Select Server,"CPU usage","Memory usage","Total FreeSpace","logged Users" |
Export-Csv "D:\code\report$(Get-Date -F dd_MM_yyy_hhmm).csv"

两个代码的输出:

1

DeviceID    Description        DiskSize(GB)     FreeSpace(GB)**
C:          Local Fixed Disk   230.21             67.33 
D:          Local Fixed Disk   222.94             79.15 

2

Server    CPU usage  Memory usage   Total FreeSpace logged Users**
Boss'Pc    48%        48.21%           146.48 GB     Boss

1 个答案:

答案 0 :(得分:-1)

为了做到这一点,创建一个数组,并用自定义对象加载它,每个自定义对象都有你想要存储在行中的属性。

$script:array = @()
$computerList |% {
  $ob = New-Object System.Object
  Function1 {
    $ob | Add-Member -type noteProperty -Name CPU -Value $_.cpu
  }
  Function2 {
    $ob | Add-Member -type noteProperty -Name DISKUSE -Value $_.disk
  }
  $script:array += $ob
}
$script:array | Export-CSV file.csv