powershell可通过get-process的starttime属性计算进程运行时长。支持单进程秒级查询、批量用户进程排序、csv快照导出及超时告警,需注意权限、空starttime判断和性能开销。
powershell 可以直接获取进程的启动时间,进而计算运行时长,实现对进程运行时间的统计分析。关键在于利用 get-process 的 starttime 属性,并结合当前时间做差值运算。
获取单个进程的实时运行时长
通过 StartTime 计算已运行秒数、分钟或小时,适合快速查看重点进程(如 explorer.exe 或自定义服务进程):
- 运行
Get-Process -Name notepad | ForEach-Object { [math]::Round((Get-Date) - $_.StartTime).TotalSeconds },输出记事本已运行的秒数(四舍五入) - 更可读的写法:
$p = Get-Process -Name chrome; if ($p) { $dur = (Get-Date) - $p[0].StartTime; "$($p[0].ProcessName): $($dur.Hours)h $($dur.Minutes)m" } - 注意:若进程无
StartTime(如某些系统进程或权限不足时),会报错,建议加if ($_.StartTime)判断
批量统计所有用户进程的运行时长
筛选非系统进程(排除 svchost、wininit 等),按运行时长倒序排列,便于发现长期驻留的可疑或冗余进程:
Get-Process | Where-Object { $_.StartTime -and $_.UserName -match 'DOMAIN\User|.*\.*' } | Select-Object Name, Id, @{n='Uptime';e={((Get-Date) - $_.StartTime).ToString('hh:mm:ss')}}, StartTime | Sort-Object Uptime -Descending | Format-Table -AutoSize-
UserName字段需启用进程用户信息权限(管理员运行或配置SeSecurityPrivilege),否则为空;普通用户可用Get-WmiObject Win32_Process替代并关联Win32_LoggedOnUser - 输出格式统一为
hh:mm:ss,避免毫秒干扰判断
导出历史运行时长快照用于趋势分析
定时采集关键进程(如数据库服务、自动化脚本)的启动时间和持续时长,保存为 CSV,后续可用 Excel 或 Power BI 做趋势对比:
- 脚本示例:
$log = @(); $targets = 'sqlservr','python','powershell'; foreach($name in $targets) { $procs = Get-Process -Name $name -ErrorAction SilentlyContinue; foreach($p in $procs) { $log += [PSCustomObject]@{ Name=$p.Name; Id=$p.Id; StartTime=$p.StartTime; UptimeSec=[int]((Get-Date)-$p.StartTime).TotalSeconds; Timestamp=Get-Date } } }; $log | Export-Csv "proc_uptime_$(Get-Date -f yyyyMMdd_HHmm).csv" -NoTypeInformation - 建议配合 Windows 任务计划程序每5–15分钟执行一次,文件名带时间戳避免覆盖
- 注意避免高频采集导致性能开销,尤其在低配设备上
识别异常长周期进程并自动告警
设定阈值(如 Chrome 运行超24小时、PowerShell 脚本超8小时),触发邮件或弹窗提醒,适用于运维巡检或开发环境监控:
$threshold = [timespan]::FromHours(24); Get-Process chrome | Where-Object { $_.StartTime -and ((Get-Date) - $_.StartTime) -gt $threshold } | Send-MailMessage -To "admin@local" -Subject "Chrome 进程运行超24小时" -Body "PID $($_.Id) 启动于 $($_.StartTime)" -SmtpServer "localhost"- 也可用
[System.Windows.Forms.MessageBox]::Show()实现桌面提示(需加载System.Windows.Forms) - 生产环境建议将告警逻辑封装为函数,加入重试机制与日志记录,避免误报刷屏











