≡ Menu

Find out who killed a process in Windows

In this article I will cover a procedure that helps you to find out who has killed a process that you care about.

Often we get this problem. The process we care about closes abruptly and we are not quite sure whether it exited on its own or someone killed it via task manager or using kill (or stop-process). The procedure I am going to discuss will help you in finding out that.

A process in windows environment has 3 possible ways of exit.

  1. Process terminating on its own after completion of its work
  2. Someone terminating it from task manager or using kill.exe like utilities
  3. Process is crashed by OS when it misbehaves

It is easy to determine #3 as we see an application error event in event log when a process crashes. But how to determine the #1 and #2 cases. Process doesn’t log any event in application log when exiting. Also you cannot determine it by using some process trackers like “PowerShell: Track process stop/termination” because it doesn’t tell you who killed the process or it terminated on its own. It just says process exited.

The solution

So what is the solution here? Debugging tool for windows has a nice utility called gflags.exe which can be used to find out this information. After you download and install the Debugging tool for windows, launch gflags.exe from the installation directory. It requires admin privileges to open so be sure to be administrator on the computer where you are launching this.

Follow the below instructions to configure Windows process exit monitoring.

  1. Launch gflags.exe from Windows Debugging tool kit installation directory
  2. Switch to “Silent Process Exit” tab
  3. Type the name of the process that you want to monitor. In my case, I have given notepad.exe
  4. Press tab and check the box “Enable silent process exit monitoring”
  5. Click OK to complete.
gflags enable process exit monitoring

Now open notepad application and close it gracefully (by clicking close button from right top corner) and you will see event log below in Application event log with event ID 3000 from source “Process Exit Monitor

event1

Now open a notepad application and this time kill the process via task manager. Now you will see a 3001 event ID in application log from the same source.

event2

How to download Debugging tools for windows?

Just do a simple google search and you will be taken to a Microsoft download page. Please note that Debugging tools are part of Windows SDK & Windows Driver Kit download package as well. You need to select Debugging tools for windows during the installation.

How to disable the silent process exit monitoring?

Now that you know how enable silent process exit monitoring. You might also want to know how to disable it after the task is accomplished. It is very easy

  1. Launch gflags.exe
  2. Switch to “Silent Process Exit” tab
  3. Type the name of the process for which you want to disable monitoring
  4. Press tab and ensure “Enable silent process exit monitoring” box is unchecked
  5. Click OK to disable the monitoring for that process
{ 6 comments }

PowerShell: Track process stop/termination

I showed you how to track process startup using PowerShell in my previous post. Now let us see how to track the process stop or termination using PowerShell.

PowerShell: How to track process startup/new processes

The approach we use for tracking process stop is similar to process startup where we rely on querying WMI class for process termination events. We need to query __InstanceDeletionEvent  WMI class to get details when a process is terminated. The process object returned via $event.SourceEventArgs.NewEvent.TargetInstance is not having process termination date time. I couldn’t find any other way to fetch process termination time so I decided to reduce the polling interval to 2 seconds so that I can rely on event generation time to get nearest value to actual termination time. So when you see the time of termination, expect it to be anywhere within last 2 seconds.

Code:

function Enable-ProcessStopTrace {            
[CmdLetBinding()]            
param(            
)             
$Query = "Select * From __InstanceDeletionEvent within 2 Where TargetInstance ISA 'Win32_Process'"            
$Identifier = "StopProcess"            
$ActionBlock = {            
 $e = $event.SourceEventArgs.NewEvent.TargetInstance            
 write-host ("Process {0} with PID {1} has stopped at {2}" -f $e.Name, $e.ProcessID, $event.TimeGenerated)            
}            
Register-WMIEvent -Query $Query -SourceIdentifier $Identifier -Action $ActionBlock            
            
            
}

Output:

enable-processstoptrace

Happy learning..

{ 2 comments }

Process Tracking in Windows environment is tough in general sense. That means, it is difficult to track when a process is started, what are the command line arguments it got, what is the path of executable, Process ID and several other parameters. This kind of facility helps in cases when you are troubleshooting a problem or you want to know who is starting a process on a server. I got similar requirement and figured out that it can be done easily with PowerShell.

PowerShell has a cmdlet called Register-WmiEvent which can be used for configuring events. We can use this cmdlet to configure monitoring around the process creation and we can log several details like when the process is started, what are the arguments, who started it etc. The approach I am going to use below relies on WMI event capabilities. It is much better approach that constantly scanning the current list of processes to know when a process is started. Also it is difficult to track the processes which live for very short interval. The WMI eventing capabilities addresses such problems easily and we can keep a watch on all processes that are starting.

Code

function Enable-ProcessTrace {            
[CmdLetBinding()]            
param(            
)             
$Query = "Select * From __InstanceCreationEvent within 3 Where TargetInstance ISA 'Win32_Process'"            
$Identifier = "StartProcess"            
$ActionBlock = {            
 $e = $event.SourceEventArgs.NewEvent.TargetInstance            
 write-host ("Process {0} with PID {1} has started" -f $e.Name, $e.ProcessID)            
}            
Register-WMIEvent -Query $Query -SourceIdentifier $Identifier -Action $ActionBlock            
}

As you can see in the above code, I am querying _InstanceCreationEvent WMI class for any new instances of Win32_Process class every 3 seconds. When any process started, the code in the Action block will be executed. We can leverage this facility perform any actions based on process start.

The query string is based on WQL where ISA and WITHIN are keywords. The $event contains the information about the process that started. To see process details you can access the properties of $event.SourceEventArgs.NewEvent.TargetInstance object. Modify the contents of action block to suite your needs.

Usage:

Copy & paste the above code in PowerShell window and call the function like below.

enable-processtrace

Output:

You need to keep the powershell window opened so that you can see messages like below when a process is started.

processstartoutput

Happy learning…

You can find details similar code for tracking process top at below link

PowerShell: Track process stop/termination

{ 1 comment }

PowerCLI: Connect to Console of a VM

If you have PowerCLI 5.5 R1 release or above then you can use Open-VMConsoleWindow cmdlet to connect to console of a VM. When this cmdlet is used it opens a browser window which shows the console of VM that you wanted to view. This is quite handy to view console of VM without actually connecting using Virtual Center client. Looks like the current version supports 32-bit version of Internet Explorer, Firefox and Chrome only. No 64-bit.

How to use?

Get-VM -Name myvmpc1 | Open-VMConsoleWindow

How it looks like?

clip_image002

Image source : https://blogs.vmware.com/PowerCLI

 

More information:

You read more about this feature and how it works under the covers at https://blogs.vmware.com/PowerCLI/2013/10/opening-the-virtual-machine-remote-console-through-powercli.html

{ 0 comments }

In VMware, Observed IP Range means the list of IP addresses subnets a ESX host can see and their VLAN IDs. ESX host gets this information from the switch to which it is connected using CDP protocol. If the switch doesn’t allow CDP information advertizement then you will not see this information.

In this post, I will show you how to query list of IP ranges a ESX host can see and their VLAN IDs information using PowerShell for a given ESX host(prodesx1.techibee.com). This information you can get from UI as well in the network adapter section of the configuration tab of ESX host.

You need to execute these commands from PowerCLI as the code involves VMware Cmdlets.

First we need to query ESX host obj.

$VMhostobj = Get-VMHost -Name prodesx1.techibee.com

Once you have the VMHost object, we need to get the view of it and then query network adapter configuration view.

$VMHostView = Get-View $VMHostObj            
$networkView = Get-View $VMHostView.ConfigManager.NetworkSystem

This view will contain the network information which shows the physical network adapters that contain the CDP information. So, we need query each adapters CDP information using QueryNetworkHint() method

$physicalnics = $networkview.networkinfo.pnic            
foreach($nic in $physicalnics) {            
    $hints = $networkview.querynetworkhint($nic.device)            
    foreach($hint in $hints) {            
        $hint.subnet            
    }            
}

 

The $hint variable in above code contains several other information like switch port the ESX host connected, name of the switch etc. This contains the information that you see from Virtual Center UI.

I derived this code with inspiration from VMware KB article http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1007069 . it is the source for above image as well.

{ 0 comments }

PowerShell: Execute a command from history

PowerShell has facility where in your can view the commands executed in the current shell. You can use Get-History cmdlet to see all the previously executed commands. Note that PowerShell V3 & above will show all commands you executed while the PowerShell V2 shows only last 32 commands you executed.

Now the question is how do we execute a command from list returned by Get-history. One way is to copy paste the commands manually but that is not efficient. PowerShell has some near way of doing it. Let us see how to do that.

To access any item in history by using ID, you can try the below command. This command will fetch the item from history which has ID number 3.

PS C:\>#3 <tab>

Similar you can fetch the commands from history by using keywords as well. For example, below command will get commands from history that has given keyword anywhere in the command. If multiple commands are there from history that matches the keyword, you can keep pressing the tab till you reach the one you need in history.

PS C:\>#keyword <tab>

Looks very easy and efficient, Correct? Let us jump into some practices now. This video will demonstrate how to use it.

Happy learning…

{ 0 comments }

Powershell: Find text file encoding type

I came across a situation today to find out what kind of a encoding a file is using. I want to understand the encoding because if I process the text file without that, the results might change. My search on Internet made me land at http://poshcode.org/2153 which gave a nice script for identifying the encoding of a given file.

You can get complete code from http://poshcode.org/2153

 

{ 0 comments }

Powershell: Verify network connectivity

There are several ways to verify if a computer is connected to network. Some prefer querying the IP address details, enable status, and ping test to default gateway. Each kind of approach has its advantages and some kind of approaches are preferred based on the requirements.

In this post I will show you easiest way I found to verify the network connectivity status of a computer.

The System.Net.NetworkInformation.NetworkInterface class has a method called GetIsNetworkAvailable to verify the network connection status of the local computer. This method returns True when the network connectivity is available and False when no network connectivity found.

Look at the below example for better understanding.

if([System.Net.NetworkInformation.NetworkInterface]::GetIsNetworkAvailable()) {            
    Write-Host "$env:ComputerName connected to network"            
} else {            
    Write-host "$env:ComputerName not connected to network"            
}

Hope this tip helps..

Let me know if you come across any other easy/better way.

{ 0 comments }

PowerShell: What is new PowerShell v5?

As you might already aware, PowerShell v5 preview is out and like any other powershell enthusiasts, I want to understand what is special in this release. I hunt for features list is going on and I will keep this post updated as I progress with my findings.

PowerShell V5 preview is released on 3rd April 2014 and you can find release notes at Windows Server Blog

What is new in this release?

If you know any other new features in this release, please drop a note in comments section. I will be glad to review it and post it here. Thanks.

{ 1 comment }

What is chocolatey in PowerShell v5?

Microsoft released PowerShell v5 Preview yesterday. I did quick search on internet about what is special about this release. Though I couldn’t find any exiting articles, the one that grabbed my attention is OneGet module.

What is OneGet module and what it has?

Get-Command -Module oneget
chocolety1

So basically, it is a module that allows packaged software installation from a web based sources like chocolatey in a silent manner. That means, you can use these cmdlets to install, uninstall softwares available at Chocolate (a web based software repository for Windows OS).

When I ran Get-PackageSource to get the list of sources, it gave me below message. Looks like it needs some base component (NuGet Manager in this case) to install any packages from sources. So, I let this installation continue. It completed quick as I see some progress like it is downloading packages from a web URL.

chocolety

After download and installation, I can see Chocolatey as one of the package source. My assumption is we can have any no. of package sources here if one is available.

chocolety2

Ok, well, I have the package source, what next? Its time to install a software. Per the Chocolatey website, they have  1739 packages available for installation on Windows. We can get these details using one of the available cmdlets, Find-Package, as well.

(Find-Package).Count

If you want to search for any softwares, you can do that as well with this cmdlet. Vim is one of my favorite editors. So searched for this package and I got the list.

Find-Package | ? {$_.Name -match "vim" }

chocolety3

Out of the returned list, the one I want to install is VIM. So let us see how we can install this package.

Install-Package is the cmdlet that can be used for package installation. It can accept either Name or Package object to install the software.

Install-Package -Name Vim

chocolety4

As you can see in the above screen package installation is progressing by downloading the content from internet. Now we can verify the installed packages using Get-Package cmdlet.

Uninstallation of these packages is also straight forward using Uninstall-Package cmdlet.

Boe Prox has written a similar article on this automated & silent package installation using OneGet and his explanation is much deeper. You can have peek at his blog post http://learn-powershell.net/2014/04/03/checking-out-oneget-in-powershell-v5/ for more details

Conclusion:

In general, I found this module and installation via a centralized source via web quite useful. Home PC users might like this but when it comes to enterprise usage, I doubt how far the firms will use this because the packages are maintained by a third party on the web. May be if similar sources can be built in house  easily and package installation, uninstallation can be done easily, then I am sure it will become a quite useful tool for any enterprise for managing softwares.

Hope this review helps.

{ 0 comments }