使用进程年龄的 Powershell 停止进程表现得很奇怪

Powershell stop process using process age behaving wierd

我的小脚本是这样工作的

$age = read-host "enter age"
Get-Process | Where-Object { $_.Name -eq "notepad" -and ($_.starttime).totalminutes -le $age} | Stop-Process (New-TimeSpan -Start (get-process notepad).StartTime).totalminutes

如果我将 -le 更改为 -gt-ge(这是我正在尝试使用的)它不会终止进程......我真的不知道明白为什么这不起作用。

谁能分享一些见解?

谢谢!

我不完全理解您要实现的目标,但我假设您想要终止记事本进程,该进程 运行 超过定义的分钟数。在这种情况下,您可以使用这样的脚本

# Get process
Get-Process | 
# which has the name of notepad and current date minus start date in minutes is less than defined age
Where-Object { $_.Name -eq "notepad" -and ((Get-Date) - $_.starttime).TotalMinutes -gt $age } | 
#Kill the process
Stop-Process

这里的技巧是获取当前日期和开始日期的分钟数之差,可以这样实现:

((Get-Date) - $_.starttime).TotalMinutes