More Powershell Nuggets

In a previous post I provided a few small Powershell code blocks suitable for beginners to digest. Here are a few more that anyone starting with Powershell might like to experiment with.

A simple For Loop in Powershell

Here’s just a simple for loop in Powershell.

?View Code POWERSHELL
# A simple for loop
for($i = 0; $i -le 10; $i++)
{
	Write-Host "Loop = $i";
}

For Loop in Powershell

A simple For Loop using an array in Powershell

Like all modern scripting languages, Powershell offers us an easy way to iterate over arrays.

?View Code POWERSHELL
# Setup an array
$array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
# A foreach loop using an array
foreach($item in $array)
{
	Write-Host 'Array item =' $item
}

Iterating over an array with Powershell

Iterate recursively through a directory structure with Powershell

This nugget iterates through the user profile folder structure, C:\Users\Rhys on my laptop, and reports if each txt file encountered is less than 100 bytes or greater than 100 bytes.

?View Code POWERSHELL
$dir = dir -Recurse $Env:USERPROFILE *.txt;
foreach($file in $dir)
{
	$bytes = $file.Length;
	if($bytes -lt 100)
	{
		Write-Host -ForegroundColor Green "$file < 100 bytes.";
	}
	else
	{
		Write-Host -ForegroundColor Cyan "$file >= 100 bytes.";	
	}
}

Directory recursion with Powershell

Find all .mdf and .ldf files on your C:\ drive with Powershell

These two simple lines will search through your C:\ drive looking for .mdf and .ldf files. You can easily search for different files by changing the extensions specified in the –Include switch.

?View Code POWERSHELL
# Find all mdf and ldf files in C:\ on Local machine
$textFiles = Get-ChildItem -Path C:\ -Recurse * -Include "*.mdf", "*.ldf";
$textFiles | Format-Table -AutoSize -Property Name, Length;

Find files by extension with Powershell

Find all .mdf and .ldf files on a remote Computer with Powershell

This example is similar in function to the last one, except we’re using WMI here to query remote computers. The -ComputerName switch specifies the computer we wish to query and the -Filter switch specifies the extensions we wish to search for.

?View Code POWERSHELL
# Find all mdf and ldf files on a remote host
$dbFiles = Get-WmiObject -Class CIM_DataFile -Filter "Extension = 'mdf' OR Extension = 'ldf'" -ComputerName "localhost";
$dbFiles | ForEach-Object { Write-Host $_.Name; }

Find files on remote computers with Powershell

Query Processes on local and remote Computers with Powershell

Just a few lines of code in Powershell allow you to do some pretty powerful things. Beginners should definitely check out the Get-WmiObject cmdlet and see how useful it is. The first line of code here creates an instance of the Win32_Process class. ComputerName specifies the computer you wish to query. The Filter flag contains the criteria by which we wish to filter the data. This is just like the WHERE clause in SQL. The second line simply takes the output and formats it nicely including only the columns we specify.

?View Code POWERSHELL
$Processes = Get-WmiObject -Class Win32_Process -ComputerName 'localhost' -Filter "PageFileUsage > 0 AND Name Like '%s%'";
$Processes | Format-Table -AutoSize -Property Name, ProcessId, ThreadCount, PageFileUsage, PeakPageFileUsage, PeakVirtualSize, PeakWorkingSetSize;

Query Processes on local and remote computers with Powershell

Kill a Process on a remote Computer with Powershell

The script is setup to kill calc.exe on localhost but it can be changed to run for any computer, or process, that you have appropriate permissions for. To test this script make sure you have calc.exe running.

?View Code POWERSHELL
# Kill a process on a remote machine
$computer = "localhost";
$processToKill = "calc.exe";
$process = Get-WmiObject -Class Win32_Process -Filter "Name = '$processToKill'" -ComputerName $computer;
if($process -eq $null)
{	# If null then the process may not be running
	Write-Host -ForegroundColor Red "Couldn't get process $processToKill on $computer";
	sleep(10);
	exit;
}
else
{
	Write-Host "Attempting to Kill $processToKill on $computer";
}
# Kill the process and get exit status 0 = OK
$status = $process.InvokeMethod("Terminate", $null);
switch($status)
{
	0 { Write-Host -ForegroundColor Green "Killed $processToKill on $computer"};
	default { Write-Host -ForegroundColor Red "Error, couldn't kill $processToKill on $computer"};
 
};

Kill processes on remote computers with Powershell


5 Comments

  1. Brock says:

    This script works until you have multiple processes with the same name. Try opening two or more notepads and kill them. You get a big fat error. Anyway around it?

  2. Rhys says:

    Yep, probably quite simple to get all process ids with a specific name and then kill them one-by-one. I might have a stab at it in a day or two if you don’t.

    Cheers,

    Rhys

  3. Rhys says:

    Hi Brock,

    Here’s how you can resolve the issue you pointed out…

    http://www.youdidwhatwithtsql.com/kill-all-processes-by-name-with-powershell/853

    Cheers,

    Rhys

  4. Kev says:

    Ok, this script is great for killing one process, how can It be modified to kill say three different processes?
    eg. Notepad.exe, Calc.exe and wintrv.exe ?

  5. Rhys says:

    Hi Kev,

    Easy, just setup an array and iterate through the value. The sample below will give you a good idea for something more robust…

    # Kill a process on a remote machine
    $computer = "localhost";
    $processesToKill = @("calc.exe", "notepad.exe", "wintrv.exe");

    foreach($process in $processesToKill)
    {

    $process = Get-WmiObject -Class Win32_Process -Filter "Name = '$process'" -ComputerName $computer;
    if($process -eq $null)
    { # If null then the process may not be running
    Write-Host -ForegroundColor Red "Couldn't get process $process on $computer";
    }
    else
    {
    Write-Host "Attempting to Kill $process on $computer";
    }
    # Kill the process and get exit status 0 = OK
    $status = $process.InvokeMethod("Terminate", $null);
    switch($status)
    {
    0 { Write-Host -ForegroundColor Green "Killed $process on $computer"};
    default { Write-Host -ForegroundColor Red "Error, couldn't kill $process on $computer"};

    };
    }

    Cheers,

    Rhys

Leave a Reply