Where-Object command

Filtering the output from commands may be performed using Where-Object. For example, we might filter processes that started after 5 pm today:

Get-Process | Where-Object StartTime -gt (Get-Date 17:00:00) 

The syntax shown in help for Where-Object does not quite match the syntax used here. The help text is as follows:

Where-Object [-Property] <String> [[-Value] <Object>] -GT ...

In the preceding example, we see the following:

  • StartTime is the argument for the Property parameter (first argument by position
  • The comparison is greater than, as signified by the gt switch parameter
  • The date (using the Get-Date command) is the argument for the Value parameter (second argument by position)

Based on that, the example might be written as follows:

Get-Process | Where-Object -Property StartTime -Value (Get-Date 17:00:00) -gt 

However, it is far easier to read StartTime is greater than <some date>, so most examples tend to follow that pattern.

Where-Object will also accept filters using the FilterScript parameter. FilterScript is often used to describe more complex filters, filters where more than one term is used:

Get-Service | Where-Object { $_.StartType -eq 'Manual' -and $_.Status -eq 'Running' }

When a filter like this is used, the conditions are evaluated in the order they are written. This can be used to avoid conditions that may otherwise cause errors. 

In the following example, Test-Path is used before Get-Item, which is used to test the last time a file was written on a remote computer (via the administrative share):

'Computer1', 'Computer2' | Where-Object {
(Test-Path "\$_c$ empfile.txt") -and
(Get-Item "\$_c$ empfile.txt").LastWriteTime -lt (Get-Date).AddDays(-90)
}

If Test-Path is removed, the snippet will throw an error if either the computer or the file does not exist.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.195.128