Variables
6 snippetsString
$name = "John"Number
$age = 25Array
$fruits = @("apple", "banana", "cherry")Hashtable
$person = @{ Name = "John"; Age = 30 }Boolean
$isActive = $trueEnv Variable
$env:PATHControl Flow
5 snippetsIf/Else
if ($x -gt 0) {
Write-Host "positive"
} elseif ($x -lt 0) {
Write-Host "negative"
} else {
Write-Host "zero"
}For Loop
for ($i = 0; $i -lt 5; $i++) {
Write-Host $i
}Foreach
foreach ($item in $array) {
Write-Host $item
}While
while ($count -lt 10) {
$count++
}Switch
switch ($day) {
"Mon" { "Monday" }
"Tue" { "Tuesday" }
default { "Other" }
}Comparison Operators
4 snippetsEquals
-eq # Equal
-ne # Not equalCompare
-gt # Greater than
-lt # Less than
-ge # Greater or equal
-le # Less or equalString
-like # Wildcard match
-match # Regex match
-contains # Collection containsLogical
-and # AND
-or # OR
-not # NOTTired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Functions
3 snippetsFunction
function Greet {
param([string]$Name)
return "Hello, $Name!"
}Advanced Function
function Get-Data {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Path
)
Get-Content $Path
}Default Param
function Greet {
param([string]$Name = "World")
"Hello, $Name!"
}Pipeline
5 snippetsWhere-Object
Get-Process | Where-Object { $_.CPU -gt 10 }Select-Object
Get-Process | Select-Object Name, CPUSort-Object
Get-Process | Sort-Object CPU -DescendingForEach-Object
1..5 | ForEach-Object { $_ * 2 }Measure-Object
Get-Process | Measure-Object -Property CPU -SumFile Operations
6 snippetsRead File
Get-Content "file.txt"Write File
"Hello" | Out-File "file.txt"Append File
"More text" | Add-Content "file.txt"Test Path
if (Test-Path "file.txt") { ... }Copy/Move
Copy-Item "src.txt" "dest.txt"
Move-Item "old.txt" "new.txt"Remove
Remove-Item "file.txt"Error Handling
3 snippetsTry/Catch
try {
Get-Content "missing.txt" -ErrorAction Stop
} catch {
Write-Host $_.Exception.Message
}Finally
try { ... } catch { ... } finally { Cleanup }Throw
throw "Something went wrong"