Powershell杀死除系统之外的所有进程

时间:2014-09-10 15:28:10

标签: powershell powershell-v2.0 powershell-v3.0 powershell-remoting powershell-ise

在powershell中,我想杀死所有用户的所有进程,除了系统使用的资源管理器和进程

这是我包含错误的地方:

$Cred = Get-Credential;
Invoke-Command -ComputerName localhost -Credential $Cred -ScriptBlock { Get-Process $env:ALLUSERSPROFILE | Where-Object -FilterScript {$_.Name -ne "SYSTEM, NETWORK SERVICE, LOCAL SERVICE"} | Where-Object -filterscript {$_.Name -ne "explorer"} | Stop-Process -WhatIf }
Cannot find a process with the name "C:\ProgramData". Verify the process name and call the cmdlet again.
    + CategoryInfo          : ObjectNotFound: (C:\ProgramData:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand
    + PSComputerName        : localhost

1 个答案:

答案 0 :(得分:0)

在这里,这应该适合你。

Function Stop-UserProcesses{
Param([string]$Computer = "localhost")
    $Cred = Get-Credential
    Invoke-Command -ComputerName $Computer -Credential $Cred -ScriptBlock { 
        Get-Process -IncludeUserName | Where{!($_.UserName -match "NT AUTHORITY\\(?:SYSTEM|(?:LOCAL|NETWORK) SERVICE)") -and !($_.ProcessName -eq "explorer")}|Stop-Process -WhatIf
    }
}

一旦你确信它具有功能,请删除-WhatIf。然后将其称为Stop-UserProcesses以在本地结束所有内容,或Stop-UserProcesses SomeComputer01以结束远程系统上的所有内容(假设您的环境中已启用远程会话)。

编辑:那么,显然-IncludeUserName开关是v4中的新功能。因此,为了做你想做的事情,我们必须跳过箍并在win32_process类上使用Get-WMIObject,然后为每个进程执行GetOwner()方法。可能想要对它进行过滤,这样我们就不会在没有所有者的情况下遇到空闲抛出错误等问题,因此我们将确保CommandLine属性存在。

Function Stop-UserProcesses{
Param([string]$Computer = "localhost")
    $Cred = Get-Credential
    Invoke-Command -ComputerName $Computer -Credential $Cred -ScriptBlock { 
        #Get all processes
        $Processes = get-wmiobject win32_process|Where{![string]::IsNullOrEmpty($_.commandline)}|Select *,@{l='Owner';e={$_.getowner().user}}
        #Filter out System and service processes
        $Processes = $Processes | Where { !($_.Owner -match "(?:SYSTEM|(?:LOCAL|NETWORK) SERVICE)") }
        #Get processes and filter on the Process ID and name = explorer, then pipe to stop-process
        Get-Process | Where { $Processes.ProcessID -contains $_.id -and $_.name -ne "explorer" } | Stop-Process -WhatIf
    }
}