PowerShell Tip of the Week: Taskkill remotely

Taskkill command can be very useful when it comes to daily operational tasks. I often had situation that several ADFS web servers were not working properly. Recently I’ve been flooded by SCOM alerts about service failure. First recommended step is to restart ADFS service. Unfortunately normal service restart does not solve the issue. Taskkill command comes to rescue – it allows to terminate completely affected process.

Taskkill

Ends one or more tasks or processes. Processes can be killed by process ID or image name. To kill process on remote server ADFS01 we can use the following example:

TASKKILL /s ADFS01 /f /IM Microsoft.IdentityServer.ServiceHost.exe

Of course you can use this command in other ways. Here are some useful examples from technet site:

taskkill /pid 1230 /pid 1241 /pid 1253 
taskkill /f /fi "USERNAME eq NT AUTHORITY\SYSTEM" /im notepad.exe 
taskkill /s srvmain /f /im notepad.exe 
taskkill /s srvmain /u maindom\hiropln /p p@ssW23 /fi "IMAGENAME eq note*" /im * 
taskkill /s srvmain /u maindom\hiropln /fi "USERNAME ne NT*" /im * 
taskkill /f /fi "PID ge 1000" /im *

For more info about Taskkill please visit technet site.

Below you can find simple script for killing ADFS service – Microsoft.IdentityServer.ServiceHost.exe. At the beginning you need to provide server list. In foreach loop script will check if server is accessible – $Check = Test-Path \\$Server\c$. If this check passed then it will terminate ADFS process:

# Servers list
$Servers = Get-Content -Path "C:\users\$env:username\desktop\ADFS_servers.txt"

# Looping each server
Foreach($Server in $Servers)
{
    $Server = $Server.trim()
    Write-Host "$Server - " -NoNewLine -ForegroundColor Yellow

    # Checking if server is accessible  
    $Check = Test-Path \\$Server\c$

    If($Check -match "True")
    {
        # Using taskkill command on remote server
        TASKKILL /s $Server /f /IM Microsoft.IdentityServer.ServiceHost.exe
    }
    Else
    {
        Write-Host "ERROR: Failed to connect"
    }
}

Output should look like this:

taskkill
taskkill

It can be done in easier way:

Get-Content -path C:\users\$env:username\desktop\ADFS_servers.txt | foreach { TASKKILL /s $_ /f /IM Microsoft.IdentityServer.ServiceHost.exe }

You check also one of the previous articiles about killing process function – link.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.