In PowerShell, the “where” keyword is used to filter the results of a command or expression based on specified criteria. It is often used in conjunction with the “select-object” cmdlet to filter the objects that are returned by a command.
Another Powerful feature you can use in PowerShell is the Where Statement.
With the Where statement, you can search the PowerShell properties for your item.
In this example, we will use the following file structure for showing how and when to use the Where statement.
Now it’s time to play with the where statement.
First, we need to find out which properties we can filter with where. To find out the properties you can do the “| Get-Member” .
Let’s play with the name property first. Filter all filenames on the letter o.
Show the files with a “o” in the name:
Filter all files created with Microsoft Word. This is possible with the extension property filter. In this example, we use the equals (-eq) conditional operator.
If you not know which property a PowerShell object have you can always use the happy guessing factor. {$_} without a property behind it.
With a more advanced Where query you can get files that are created before a date using PowerShell.
In the first query, show all files which are edited after Yesterday. Greater than (-gt) yesterday. Or Lower than (-lt) Yesterday. Created the files today.. so nothing is created before Yesterday.
Below are all queries we discussed. So you can practice it yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#.Name match Cool Get-childitem | where{$_.name -match "cool"} #.? Match HR Get-childitem | where{$_ -match "hr"} #.Extension equals .docx Get-childitem | where{$_.extension -eq ".docx"} #Where can be replaced with a question mark, i personally dont like that. Get-childitem | ? {$_.extension -eq ".docx"} #More advanced qeury. Get all files wich are edited after yesterday. get-childitem | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)} #Example with another PowerShell function filter. Get the Windows Search Service get-service | where{$_.name -match "Wsearch"} |
If you have other questions about the where statement? Ask me anything below.