PowerShell 脚本来监控 CPU、内存和磁盘使用情况:

PowerShell 脚本来监控 CPU、内存和磁盘使用情况:

powershellCopy Code
# 获取CPU使用率
$cpu = Get-Counter '\Processor(_Total)\% Processor Time'

# 获取内存使用情况
$mem = Get-WmiObject Win32_OperatingSystem
$memUsage = [math]::round((($mem.TotalVisibleMemorySize - $mem.FreePhysicalMemory) / $mem.TotalVisibleMemorySize) * 100, 2)

# 获取磁盘使用情况
$disk = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
$diskUsage = foreach ($d in $disk) {
    [pscustomobject]@{
        Drive = $d.DeviceID
        UsedSpace = [math]::round(($d.Size - $d.FreeSpace) / 1GB, 2)
        FreeSpace = [math]::round($d.FreeSpace / 1GB, 2)
    }
}

# 输出监控结果
"CPU Usage: $($cpu.CounterSamples.CookedValue)%"
"Memory Usage: $memUsage%"
$diskUsage | Format-Table -AutoSize

运行这个脚本将显示 CPU 使用率、内存使用率和磁盘使用情况。


增强这个脚本,使其定期运行并记录性能数据到日志文件中。以下是一个示例:

powershellCopy Code
# 设置日志文件路径
$logFilePath = "C:\PerformanceLog.txt"

# 定义监控间隔(秒)
$monitorInterval = 60

# 创建一个无限循环进行监控
while ($true) {
    # 获取 CPU 使用率
    $cpu = Get-Counter '\Processor(_Total)\% Processor Time'

    # 获取内存使用情况
    $mem = Get-WmiObject Win32_OperatingSystem
    $memUsage = [math]::round((($mem.TotalVisibleMemorySize - $mem.FreePhysicalMemory) / $mem.TotalVisibleMemorySize) * 100, 2)

    # 获取磁盘使用情况
    $disk = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
    $diskUsage = foreach ($d in $disk) {
        [pscustomobject]@{
            Drive = $d.DeviceID
            UsedSpace = [math]::round(($d.Size - $d.FreeSpace) / 1GB, 2)
            FreeSpace = [math]::round($d.FreeSpace / 1GB, 2)
        }
    }

    # 获取当前时间
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

    # 记录结果到日志文件
    $logEntry = "$timestamp - CPU Usage: $($cpu.CounterSamples.CookedValue)%, Memory Usage: $memUsage%`n"
    $diskUsage | ForEach-Object {
        $logEntry += "Drive: $($_.Drive), Used Space: $($_.UsedSpace) GB, Free Space: $($_.FreeSpace) GB`n"
    }
    $logEntry += "`n"

    # 写入日志
    Add-Content -Path $logFilePath -Value $logEntry

    # 暂停指定的监控间隔
    Start-Sleep -Seconds $monitorInterval
}

说明:

  1. 日志文件路径:你可以根据需要更改 $logFilePath 的路径。
  2. 监控间隔$monitorInterval 定义了每次监控之间的时间间隔(单位为秒)。
  3. 无限循环:使用 while ($true) 创建一个无限循环,持续进行监控。
  4. 时间戳:每次记录时,会添加当前的时间戳,以便后续查阅。

运行脚本:

  1. 打开 PowerShell。
  2. 将脚本复制到一个 .ps1 文件中,例如 MonitorPerformance.ps1
  3. 右键单击 PowerShell 并选择“以管理员身份运行”。
  4. 运行脚本:.\MonitorPerformance.ps1

请确保你有权限写入日志文件的目录,并且脚本在执行期间不会被意外终止。


对脚本进行一些改进和扩展,以便更好地管理和分析性能数据。以下是一些建议:

1. 增强错误处理

可以增加错误处理,以确保在出现异常时,脚本不会崩溃:

powershellCopy Code
try {
    # 监控代码
} catch {
    $errorMessage = "Error: $_"
    Add-Content -Path $logFilePath -Value "$timestamp - $errorMessage`n"
}

2. 添加邮件通知功能

如果 CPU 或内存使用率超过某个阈值,可以通过邮件通知你。你可以使用 Send-MailMessage 命令发送电子邮件:

powershellCopy Code
# 设置阈值
$cpuThreshold = 80
$memThreshold = 80

# 发送邮件的函数
function Send-AlertEmail {
    param (
        [string]$subject,
        [string]$body
    )
    Send-MailMessage -To "youremail@example.com" -From "monitor@example.com" -Subject $subject -Body $body -SmtpServer "smtp.example.com"
}

# 在监控循环中检查阈值
if ($cpu.CounterSamples.CookedValue -gt $cpuThreshold) {
    Send-AlertEmail -subject "High CPU Usage Alert" -body "CPU usage is at $($cpu.CounterSamples.CookedValue)%."
}

if ($memUsage -gt $memThreshold) {
    Send-AlertEmail -subject "High Memory Usage Alert" -body "Memory usage is at $memUsage%."
}

3. 将数据写入 CSV 文件

如果希望更方便地分析性能数据,可以将日志数据写入 CSV 文件:

powershellCopy Code
# 设置 CSV 文件路径
$csvFilePath = "C:\PerformanceLog.csv"

# 添加标题(如果文件不存在)
if (-not (Test-Path $csvFilePath)) {
    "Timestamp,CPU Usage,Memory Usage,Drive,Used Space,Free Space" | Out-File -FilePath $csvFilePath
}

# 记录数据到 CSV
foreach ($diskInfo in $diskUsage) {
    $csvEntry = "$timestamp,$($cpu.CounterSamples.CookedValue),$memUsage,$($diskInfo.Drive),$($diskInfo.UsedSpace),$($diskInfo.FreeSpace)"
    $csvEntry | Out-File -FilePath $csvFilePath -Append
}

4. 优化性能

如果你希望优化脚本的性能,可以使用更高效的方法来获取性能数据,比如减少调用 Get-WmiObject 的频率,或者只在特定条件下记录数据。

5. 可视化分析

可以考虑使用 Power BI 或 Excel 来可视化 CSV 文件中的数据,帮助更好地理解系统性能变化。

完整脚本示例

整合上述改进后的完整脚本如下:

powershellCopy Code
# 设置日志文件路径
$logFilePath = "C:\PerformanceLog.txt"
$csvFilePath = "C:\PerformanceLog.csv"

# 设置阈值
$cpuThreshold = 80
$memThreshold = 80

# 设置SMTP邮件服务器
$smtpServer = "smtp.example.com"
$emailTo = "youremail@example.com"
$emailFrom = "monitor@example.com"

# 定义监控间隔(秒)
$monitorInterval = 60

# 添加标题(如果文件不存在)
if (-not (Test-Path $csvFilePath)) {
    "Timestamp,CPU Usage,Memory Usage,Drive,Used Space,Free Space" | Out-File -FilePath $csvFilePath
}

# 创建一个无限循环进行监控
while ($true) {
    try {
        # 获取 CPU 使用率
        $cpu = Get-Counter '\Processor(_Total)\% Processor Time'

        # 获取内存使用情况
        $mem = Get-WmiObject Win32_OperatingSystem
        $memUsage = [math]::round((($mem.TotalVisibleMemorySize - $mem.FreePhysicalMemory) / $mem.TotalVisibleMemorySize) * 100, 2)

        # 获取磁盘使用情况
        $disk = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
        $diskUsage = foreach ($d in $disk) {
            [pscustomobject]@{
                Drive = $d.DeviceID
                UsedSpace = [math]::round(($d.Size - $d.FreeSpace) / 1GB, 2)
                FreeSpace = [math]::round($d.FreeSpace / 1GB, 2)
            }
        }

        # 获取当前时间
        $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

        # 记录结果到日志文件
        $logEntry = "$timestamp - CPU Usage: $($cpu.CounterSamples.CookedValue)%, Memory Usage: $memUsage%`n"
        $diskUsage | ForEach-Object {
            $logEntry += "Drive: $($_.Drive), Used Space: $($_.UsedSpace) GB, Free Space: $($_.FreeSpace) GB`n"
        }
        $logEntry += "`n"
        Add-Content -Path $logFilePath -Value $logEntry

        # 写入数据到 CSV
        foreach ($diskInfo in $diskUsage) {
            $csvEntry = "$timestamp,$($cpu.CounterSamples.CookedValue),$memUsage,$($diskInfo.Drive),$($diskInfo.UsedSpace),$($diskInfo.FreeSpace)"
            $csvEntry | Out-File -FilePath $csvFilePath -Append
        }

        # 检查阈值并发送邮件
        if ($cpu.CounterSamples.CookedValue -gt $cpuThreshold) {
            Send-MailMessage -To $emailTo -From $emailFrom -Subject "High CPU Usage Alert" -Body "CPU usage is at $($cpu.CounterSamples.CookedValue)%." -SmtpServer $smtpServer
        }
        if ($memUsage -gt $memThreshold) {
            Send-MailMessage -To $emailTo -From $emailFrom -Subject "High Memory Usage Alert" -Body "Memory usage is at $memUsage%." -SmtpServer $smtpServer
        }

    } catch {
        $errorMessage = "Error: $_"
        Add-Content -Path $logFilePath -Value "$timestamp - $errorMessage`n"
    }

    # 暂停指定的监控间隔
    Start-Sleep -Seconds $monitorInterval
}

运行和测试

确保在实际运行之前,修改相关的邮件配置和文件路径。你可以先在测试环境中运行这个脚本,确保各项功能正常后再投入使用。

 

posted @ 2024-09-23 05:46  suv789  阅读(1328)  评论(0)    收藏  举报