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

时间:2015-02-07 09:56:38

标签: powershell

我的小脚本就像这样

$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(这是我正在尝试使用的内容),则不会终止此过程......我真的不明白为什么这不起作用。

有人可以分享一些见解吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

我并不完全明白你想要达到的目标,但我想你要杀死记事本程序,该程序的运行时间超过了规定的分钟数。在这种情况下,您可以使用此类脚本

# 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