≡ Menu

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 }

Today I got some requirement to verify the database name and DB server details of WSUS servers. This configuration is available inside HKLM\Software\Microsoft\Update Services\Server\Setup registry key of each WSUS server. So, I can query this registry value to find out what is the name of WSUS DB and DB server.

But out of curiosity, I started looked at the WSUS API that Boe Prox demonstrated in several articles on Script Guys blog as well as his personal blog. In past I have used this API query several other information like members of a WSUS group, patch approval status, and other information. So I thought it should have the DB details as well.

Luckily, I got what I need in few minutes. The root WSUS API object itself is having a method called GetDatabaseConfiguration which can return SUSDB and Database server details.

I wrapped this method inside a small function and I got what I need. Below is the sample code if you want to query this information.

function Get-WSUSDBDetails {            
[cmdletbinding()]            
param(            
[string]$WSUSServer            
)            

[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")            
$WSUSObj = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($WSUSServer,$False)            
$WSUSObj.GetDatabaseConfiguration()            

}

Happy learning…

{ 0 comments }

PowerShell: How to get exit code of a process

While working on a script that does file copy using Robocopy utility, I had the need to capture the exit code from the process I started. I relied on System.Diagnostics.Process dotnet class to start the copy operation using robocopy because it gives me an option to get the return code after the process completion.

So after my work, I started analyzing why such functionality can’t be achieved with Start-Process cmdlet. So, my conclusion is, it can be done with cmdlet as well. Let us see how to achieve that.

$process = Start-Process robocopy -ArgumentList "c:\scripts c:\temp\backup /MIR" -WindowStype Hidden -PassThru

By default start-process will not return process object it started. To get the process object, we need use the -PassThru parameter. The returned object has the capability to refresh its state automatically(I haven’t seen this with process objects returned by Get-Process). You can check HasExited value of the process obj attribute to determine it completed or not. It returns True when execution completed. And then ExitCode attribute will tell you the return code.

process-exit codeBelow are the some of the returns codes that robocopy exhibiting in different conditions.

exitcodes1

Happy learning…

{ 0 comments }