Exploring Match-Object in PowerShell
The Core Concept: Text vs. Objects
Section titled “The Core Concept: Text vs. Objects”- Linux/Bash: You pipe Text. Tools like
grep,awk, andsedmanipulate strings. - PowerShell: You pipe Objects (structured data). It is conceptually closer to
jq(processing JSON) than it is toawk.
1. The grep Equivalents
Section titled “1. The grep Equivalents”If you are searching inside files or raw text output.
PowerShell: Select-String (Best)
Section titled “PowerShell: Select-String (Best)”Standard regex support (.NET), case-insensitive by default.
- Alias:
sls(orgrepin generic setups). - Syntax:
Terminal window # Search all text files recursivelyGet-ChildItem -Recurse *.txt | Select-String "my_pattern"# Search with RegexSelect-String "\d{}-\d{2}" access.log
CMD: findstr (Legacy)
Section titled “CMD: findstr (Legacy)”Limited regex, legacy tool.
- Syntax:
findstr /s /i "my_string" *
2. Filtering Command Output (The “jq” Way)
Section titled “2. Filtering Command Output (The “jq” Way)”Since PowerShell commands output Objects, piping to Select-String often fails (or returns nothing) because the string representation of an object doesn’t always contain the text displayed on the screen.
Use Where-Object (Alias ?) to filter by property.
-
The Syntax:
$_represents the current object in the pipeline (likejqorawk’s$0). -
Example:
Terminal window # Filter Services (Object approach - Recommended)Get-Service | Where-Object { $_.Status -eq "Running" }# Filter Processes using RegexGet-Process | Where-Object { $_.Name -match "^sv" } -
The “Visual” Workaround: If you absolutely just want to “grep the screen” exactly as it looks, convert the objects to text streams first:
Terminal window Get-Service | Out-String -Stream | Select-String "Running"
3. The find Equivalent (File Search)
Section titled “3. The find Equivalent (File Search)”Use Get-ChildItem (Alias ls, dir, gci).
- Find by Name:
Terminal window # Linux: find . -name "*.txt"Get-ChildItem -Filter "*.txt" -Recurse - Find by Size/Date (Using Object Logic):
Terminal window # Linux: find . -size +100MGet-ChildItem -Recurse | Where-Object { $_.Length -gt 100MB } - Pathing: You can pass paths directly:
ls C:\Windows, C:\Users.
4. Cheat Sheet: Linux vs. PowerShell Operators
Section titled “4. Cheat Sheet: Linux vs. PowerShell Operators”PowerShell operators use dashes because > and < are reserved for file redirection. They are case-insensitive by default.
| Linux/Logic | PowerShell Operator | Case-Sensitive Version |
|---|---|---|
== | -eq | -ceq |
!= | -ne | -cne |
> / < | -gt / -lt | -cgt / -clt |
grep (Regex) | -match | -cmatch |
Wildcard (*) | -like | -clike |
&& (Logical) | -and | N/A |
| ` | ` (Logical) |