How to stop (terminate) processes on a remote server using PowerShell and CIM / WMI?


My friends asked me simple question: How to stop (terminate) processes on a remote server?

Of course you can use:

Invoke-Command -ComputerName RemoteServer

or

Invoke-Command -Session $existingSessionToRemoteServer

But in this case my friends had established CIM session in their script. I wrote a few simple examples how to stop process using WMI and CIM and if you add -ComputerName (for Get-WmiObject) or -CimSession (for Get-CimInstance) then you can do it on a remote server.

WMI on local computer

(Get-WmiObject Win32_Process -Filter "Name = 'calc.exe'").Terminate()

CIM on remote computer

$processItems = Get-CimInstance `
    -ClassName Win32_Process `
    -Filter "Name = 'calc.exe'" `
    -CimSession 'MyRemoteServer.ad.contoso.com'

if ($processItems ) {
    # This will not work
    # $a.Terminate()

    foreach ($processItem in $processItems) {
        Write-Verbose -Message ('{0}: Terminate process: {1} ({2})' -f $processItem.Name, $processItem.ProcessId) -Verbose

        $result = Invoke-CimMethod -InputObject $processItem -MethodName Terminate

        if ($result.ReturnValue -ne 0) {
            Write-Error -Message ('Error durring trial to terminate process; ReturnValue: {0}' -f $result.ReturnValue)
        }
    }
} else {
    Write-Verbose -Message 'Nothing to terminate' -Verbose
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2