使用PowerShell获取CPU,内存使用和可用磁盘空间

Dum*_*ont 4 powershell

你能帮我把这三个脚本组合成这样的格式吗?

ComputerName     CPUUsageAverage    MemoryUsage    C PercentFree
xxx                           12            50%              30%
Run Code Online (Sandbox Code Playgroud)

我执行这个的方式是: Get-content '.\servers.txt' | Get-CPUusageAverage

以下是脚本:

中央处理器

Function Get-CPUusageAverage
{
$input|Foreach-Object{Get-WmiObject -computername $_ win32_processor | Measure-Object -property LoadPercentage -Average | Select Average}
}
Run Code Online (Sandbox Code Playgroud)

记忆

    Function get-MemoryUsage
{
$input|Foreach-Object{
gwmi -Class win32_operatingsystem -computername $_ |
Select-Object @{Name = "MemoryUsage"; Expression = { “{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }
}
}
}
Run Code Online (Sandbox Code Playgroud)

C PercentFree

Function get-CPercentFree
{
$input|ForEach-Object{
  Get-WmiObject -Class win32_Volume -ComputerName $_ -Filter "DriveLetter = 'C:'" |
  Select-object @{Name = "C PercentFree"; Expression = { “{0:N2}” -f (($_.FreeSpace / $_.Capacity)*100) } }
 } 
 }
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 10

首先,我会避免使用$ input.您可以将查询组合成单个函数,然后输出带有每台计算机数据的pscustomobject,例如:

function Get-ComputerStats {
  param(
    [Parameter(Mandatory=$true, Position=0, 
               ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNull()]
    [string[]]$ComputerName
  )

  process {
    foreach ($c in $ComputerName) {
        $avg = Get-WmiObject win32_processor -computername $c | 
                   Measure-Object -property LoadPercentage -Average | 
                   Foreach {$_.Average}
        $mem = Get-WmiObject win32_operatingsystem -ComputerName $c |
                   Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
        $free = Get-WmiObject Win32_Volume -ComputerName $c -Filter "DriveLetter = 'C:'" |
                    Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity)*100)}
        new-object psobject -prop @{ # Work on PowerShell V2 and below
        # [pscustomobject] [ordered] @{ # Only if on PowerShell V3
            ComputerName = $c
            AverageCpu = $avg
            MemoryUsage = $mem
            PercentFree = $free
        }
    }
  }

 cat '.\servers.txt' | Get-ComputerStats | Format-Table
Run Code Online (Sandbox Code Playgroud)