我有一个运行各种可执行文件的powershell脚本。有时可执行文件会运行很长时间,我希望看到一些进程统计信息显示正在进行(有时没有任何进度,我需要停止当前进程并重新启动)。
我正在使用[system.diagnostic.process]对象来启动该过程。
$Quiet = $Process.Start()
if ($Monitor) {
if (-not $Timeout) { $Timeout = -1 }
$Process.WaitForExit($Timeout)
$LastReport = Get-Date
while (-not $Process.HasExited ) {
if (((Get-Date) - $LastReport).Minutes -gt 2) {
$Process.Refresh()
if (-not ($Process.HasExited)) {
Write-Host " Physical memory usage: $($Process.WorkingSet64)"
Write-Host " Base priority: $($Process.BasePriority)"
Write-Host " User processor time: $($Process.UserProcessorTime)"
Write-Host " Privileged processor time: $($Process.PrivilegedProcessorTime)"
Write-Host " Total processor time: $($Process.TotalProcessorTime)"
Write-Host " Page Memory Size: $($Process.PagedMemorySize64)"
if ($Process.Responding) {
Write-Host " Status = Running"
} else {
Write-Host " Status = Not Responding"
}
}
$LastReport = Get-Date
}
}
}
但是当我运行脚本时,我反复得到相同的结果:
Physical memory usage: 8605696
Base priority: 8
User processor time: 00:00:00.0624004
Privileged processor time: 00:00:00.0624004
Total processor time: 00:00:00.1248008
Page Memory Size: 3653632
Status = Running
Physical memory usage: 8605696
Base priority: 8
User processor time: 00:00:00.0624004
Privileged processor time: 00:00:00.0624004
Total processor time: 00:00:00.1248008
Page Memory Size: 3653632
Status = Running
如何在我的代码中添加函数,以确保该进程实际上正在运行而不会卡住。
请注意,此脚本是远程运行的,我依赖返回的stdout内容来监视可执行文件的运行。
答案 0 :(得分:0)
不确定答案,但现在评论太久了。
您轮询流程的方式并不是那么好。你的 while循环一直在运行,消耗处理器。尽管使用了两分钟的测试时间,但只需使用Start-Sleep(120)。使用Start-Process CmdLet使您的代码接缝能够正常工作。
这很好用,只需从系统目录的根目录dir /s
内启动一个cmd.exe
来测试:
$process = Start-Process cmd.exe -PassThru
$Process.WaitForExit(1)
while (-not $Process.HasExited )
{
Start-Sleep (3)
Write-Host " Physical memory usage: $($Process.WorkingSet64)"
Write-Host " Base priority: $($Process.BasePriority)"
Write-Host " User processor time: $($Process.UserProcessorTime)"
Write-Host " Privileged processor time: $($Process.PrivilegedProcessorTime)"
Write-Host " Total processor time: $($Process.TotalProcessorTime)"
Write-Host " Page Memory Size: $($Process.PagedMemorySize64)"
if ($Process.Responding)
{
Write-Host " Status = Running"
}
else
{
Write-Host " Status = Not Responding"
}
}