如何过滤 get-service 的输出,使其不会显示已停止的服务



我非常确定这很容易,但是由于我是新手PowerShell,所以我无法找到一种方法。以下命令:

Get-Service | Sort-Object -Property status -Descending

在PC上显示服务,按状态对其进行分类,以便在列表开头显示运行过程。启动服务后立即进行停止服务,我可以执行任何过滤器,以免显示停止服务吗?

请习惯于在在线论坛上发布该帖子和所有其他帖子时不使用缩写。

谢谢!

Get-Service | 
 Where-Object { $Psitem.Status -ne 'Stopped' } | 
 Sort-Object -Property status -Descending

这有效地按状态过滤。

取决于powershell版本($ psversiontable.psversion)您可以运行两个命令:

PS版本2.0 get-service | where {$_.status -eq 'running'}

PS版本3.0或更高的get-service | where status -eq 'running'

PS版本3.0或更大的get-service | ? status -eq 'running'

两个版本之间的很大差异是{Curly brackets},您也可以使用别名Get-Alias

以下功能将允许您选择要停止的一项服务。在您选择的时间之后,目前5分钟。该服务将再次开始。GUI选项确实允许您在选择时开始和停止。

停止服务

Function ManageService{
$Service=Get-Service | where {$_.status -eq 'running'} | Out-GridView -OutputMode Single
$GUI = new-object -comobject wscript.shell
if ($Service.Status -eq "Running"){
$ServiceName=$Service.DisplayName
$Yes_Cancle = $GUI.popup("Do you want to turn stop $ServiceName ?", `
0,"Manage Service",3)
If ($Yes_Cancle -eq 6) {
Stop-Service $ServiceName 
$GUI.popup("$ServiceName service has been STOPPED and will START again in 5 minutes, soon as you hit OK")
start-Sleep -s 300
$GUI.popup("Time is up! $ServiceName service will now start as soon as you hit OK")
Start-Service $ServiceName
cls
}
else {
$GUI.popup("You decided to cancel. $ServiceName will not be stopped")
cls
}}}
cls
ManageService

杀死一个过程

Function ManageProcess{
$Process=Get-Process | Out-GridView -OutputMode Single
$GUI = new-object -comobject wscript.shell
if ($Process.processname -ne "$False"){
$ProcessName=$Process.processname
$Yes_Cancle = $GUI.popup("Do you want to turn kill $ProcessName ?", `
0,"Manage Process",3)
If ($Yes_Cancle -eq 6) {
Stop-Process -processname $ProcessName
$GUI.popup("$ProcessName has been killed as soon as you hit OK")
cls
}
else {
$GUI.popup("You decided to cancel. $ProcessName will not be killed")
cls
}}}
cls
ManageProcess

最新更新