Operators
1. Arithmetic Operations
+ - * / %basic arithmetic- Power:
[math]::Pow(2,10)(.NET method) - Increment/Decrement:
$i++,--$i
2. Comparison Operations (type and case sensitive)
- General comparison:
-eq -ne -gt -ge -lt -le - Case-sensitive: Add
cbefore comparison operator, e.g.,-ceq -cne - Case-insensitive (default): Add
i, e.g.,-ieq -ine(same as default string comparison)
3. Wildcard and Regular Expressions
- Wildcard matching:
-like,-notlike(* ?) - Regex matching:
-match,-notmatch, after matching$Matchesautomatic variable saves groups
4. Containment and Collections
- Array contains:
-contains(left operand is collection, checks if it contains the right "element") - Reverse contains:
-in(right side is collection) - Subset checking:
Compare-Objector use set operations (see below)
5. String Operations
- Concatenation:
'a' + 'b'or interpolation"$a$b" - Repetition:
'a' * 3 # 'aaa'
6. Logical and Bitwise Operations
- Logical:
-and -or -not(short-circuit evaluation) - Bitwise:
-band -bor -bxor -bnot -shl -shr
7. Assignment and Compound Assignment
- Basic:
= - Compound:
+= -= *= /= %=
8. Type and Conversion
- Type checking:
-is -isnot - Try conversion:
-as(returns$nullon failure)
9. Redirection and Pipeline
- Pipeline:
|passes objects to the next command - Output redirection (text):
> >> 2> 2>> *>>etc. - Out-File/Set-Content/Add-Content provide encoding and append control
10. Compare Objects and Sorting
powershell
Compare-Object (1,2,3) (2,3,4) # Difference comparison
1,5,3 | Sort-Object # Sorting (stable)
Get-ChildItem | Sort-Object Length -Desc11. Pattern Matching Shortcuts
powershell
switch -Wildcard ($name) {
'ab*' { 'starts with ab' }
default { 'no match' }
}
switch -Regex ($text) {
'^(?<letter>[a-z])' { $Matches.letter }
}12. Common Pitfalls
- Distinguish
-containsand-like: the former is "collection contains element", the latter is "string wildcard matching". -eqcomparing arrays with scalars: compares item by item and returns boolean array, may cause unexpected results in if statements; use-contains/-ininstead.- String comparison is case-insensitive by default, use
-ceq/-cnefor exact matching.