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:


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


This returns the last line (count backwards):


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

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

route print | select-string