Filtering Command Results

by Jul 13, 2009

PowerShell captures any output from any command you enter. This is why you can always store command results in a variable, even with native commands. Have a look:

route print
$result = route print

In this case, $result now contains the result returned from route print. Since route print returns string data, $result is a string array. You can output everything $result captures by outputting the variable:

$result

Or, you can access individual lines. This returns the first line captured:

$result[0]

This returns the last line (count backwards):

$result[1]

You can also return more than one line at the same time:

$result[0, 2, 1]

A much more comfortable way is filtering the result. Whenever you received plain text information, use Select-String to select only those elements that contain the keyword you specify:

$result | Select-String 127.0.0.1

This will return only those lines returned by route print that contains the keyword '127.0.0.1'. Of course, you can combine everything in one line:

route print | select-string 127.0.0.1