使用PowerShell对CPU压力测试脚本

文章目录
  • 概述
  • 脚本一
  • 脚本二
  • 监控
  • 概述

    有些时候需要对处理器进行压力测试,但又不想使用第三方的C/S软件,其原因较多,比如:

    • 内网环境不允许下载
    • C/S软件体积庞大
    • 安装比较耗时耗力

    这里记录分享一下使用过的脚本。

    脚本一

    # 模拟CPU压力
    function SimulateCPULoad {
        $cpuCores = (Get-WmiObject -Class Win32_Processor).NumberOfCores
        $loadPercentage = 100  # 设置CPU负载百分比
    
        $processes = @()
        for ($i = 0; $i -lt $cpuCores; $i++) {
            $process = Start-Process -FilePath "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList "-Command while (1) { }" -PassThru
            $processes += $process
        }
    
        Start-Sleep -Seconds 99999  # 运行99999 秒钟
    
        foreach ($process in $processes) {
            Stop-Process -Id $process.Id
        }
    }
    
    # 模拟内存压力
    function SimulateMemoryLoad {
        $memorySize = (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory
        $loadPercentage = 80  # 设置内存负载百分比
    
        $memoryLoad = $memorySize * $loadPercentage / 100
        $memoryLoad = [math]::Floor($memoryLoad / 1024 / 1024)  # 转换为MB
    
        $buffer = New-Object Byte[] $memoryLoad
        while ($true) {
            $buffer += New-Object Byte[] 1024
        }
    }
    
    # 调用函数进行模拟压力测试
    SimulateCPULoad
    SimulateMemoryLoad

    脚本二

    # 获取CPU逻辑核心数
    $cores = (Get-WmiObject Win32_ComputerSystem).NumberOfLogicalProcessors
    
    # 为每个核心启动一个高负载任务
    1..$cores | ForEach-Object {
        Start-Job -ScriptBlock {
            $result = 1
            while ($true) {
                # 持续进行高强度数学运算
                $result *= [Math]::Tan([Math]::Log([Math]::Exp($result)))
                # 防止PowerShell优化掉未使用的变量
                if ($result -gt [Math]::Exp(100)) { $result = 1 }
            }
        }
    }
    
    Write-Host "已启动 $cores 个负载任务,CPU使用率正在提升..."
    Write-Host "按任意键停止压力测试..."
    [Console]::ReadKey($true) | Out-Null
    
    # 停止所有任务
    Get-Job | Stop-Job
    Get-Job | Remove-Job
    Write-Host "已停止所有负载任务"

    监控

    # 实时监控CPU使用率
    Get-Counter '\Processor(_Total)\% Processor Time' -Continuous

    1

    1. 秋虫

      不错,感谢分享!

    发表回复

    您的邮箱地址不会被公开。 必填项已用 * 标注

    回顾一次域控故障解决过程
    回顾一次域控故障解决过程
    使用PowerShell快速将GPO链接到OU
    使用PowerShell快速将GPO链接到OU
    Windows10 IPv6 无法使用记录
    Windows10 IPv6 无法使用记录
    SQL Server 日志回收记录
    SQL Server 日志回收记录
    备份Windows桌面图标个性化排序
    备份Windows桌面图标个性化排序
    Windows 新建AD域控服务器、FSMO管理
    Windows 新建AD域控服务器、FSMO管理
    微软 49 张图
    © 2025 诺诺博客如有侵权请联系删除 | 网站地图 | 百度统计 | 又拍云CDN加速
    为了获得更好的浏览效果 建议您使用IE8.0及以上版本浏览器登陆本站点 · 服务器托管于腾讯云