# Referensi Cepat PowerShell

*Cmdlet, pipeline, objek, scripting, modul*

> Source: PowerShell Documentation (learn.microsoft.com/powershell) · MIT

## Dasar

### Perintah & Bantuan

```
Get-Help Get-Process         # tampilkan bantuan cmdlet
Get-Help Get-Process -Online # buka dokumen online
Get-Command *service*        # cari perintah berdasarkan nama
Get-Alias ls                 # tampilkan target alias
```

### Alias Umum

| Command | Description |
|---------|-------------|
| `ls → Get-ChildItem` | Daftar file dan direktori |
| `cd → Set-Location` | Ganti direktori |
| `cp → Copy-Item` | Salin file atau direktori |
| `mv → Move-Item` | Pindahkan atau ganti nama |
| `rm → Remove-Item` | Hapus file atau direktori |
| `cat → Get-Content` | Baca isi file |
| `echo → Write-Output` | Cetak ke pipeline |
| `cls → Clear-Host` | Bersihkan konsol |

## Variabel

### Dasar Variabel

```
$name = "Alice"          # string
$count = 42              # integer
$pi = 3.14              # double
$list = @(1, 2, 3)      # array
$hash = @{a=1; b=2}     # hashtable
```

### Variabel Otomatis

| Command | Description |
|---------|-------------|
| `$_` | Objek pipeline saat ini |
| `$PSVersionTable` | Informasi versi PowerShell |
| `$HOME` | Direktori home pengguna |
| `$PWD` | Direktori saat ini |
| `$null` | Nilai null |
| `$true / $false` | Konstanta boolean |
| `$Error` | Array error terbaru |
| `$LASTEXITCODE` | Exit code perintah native terakhir |

### Variabel Environment

```
$env:PATH                     # baca env var
$env:MY_VAR = "value"         # set env var
Get-ChildItem Env:            # daftar semua env var
```

## Operator

### Operator Perbandingan

| Command | Description |
|---------|-------------|
| `-eq  -ne` | Sama / tidak sama |
| `-gt  -lt` | Lebih besar / lebih kecil |
| `-ge  -le` | Lebih besar/kecil atau sama |
| `-like  -notlike` | Cocok wildcard (`*`, `?`) |
| `-match  -notmatch` | Cocok regex |
| `-contains` | Koleksi mengandung nilai |
| `-in  -notin` | Nilai ada dalam koleksi |

### Operator Logika & Lainnya

| Command | Description |
|---------|-------------|
| `-and  -or  -not` | Operator logika |
| `!` | NOT logika (alias) |
| `-replace` | Ganti regex: `'hi' -replace 'h','b'` |
| `-split  -join` | Pecah / gabungkan string |
| `..` | Range: `1..5` → 1,2,3,4,5 |
| `?:` | Ternary (v7+): `$x ? 'yes' : 'no'` |

## Alur Kontrol

### if / elseif / else

```
if ($age -ge 18) {
    "Adult"
} elseif ($age -ge 13) {
    "Teen"
} else {
    "Child"
}
```

### switch

```
switch ($color) {
    "red"   { "Stop" }
    "green" { "Go" }
    default { "Unknown" }
}
```

### Loop

```
foreach ($item in $list) { $item }
for ($i=0; $i -lt 5; $i++) { $i }
while ($x -lt 10) { $x++ }
1..5 | ForEach-Object { $_ * 2 }
```

## Fungsi

### Mendefinisikan Fungsi

```
function Get-Greeting {
    param([string]$Name = "World")
    "Hello, $Name!"
}
Get-Greeting -Name "Alice"
```

### Parameter Lanjutan

```
function Copy-SafeFile {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][string]$Dest
    )
    Copy-Item $Path $Dest -WhatIf:$WhatIfPreference
}
```

## Objek & Pipeline

### Dasar Pipeline

```
Get-Process | Sort-Object CPU -Desc | Select-Object -First 5
Get-Service | Where-Object Status -eq "Running"
Get-ChildItem | Measure-Object -Property Length -Sum
```

### Cmdlet Pipeline Utama

| Command | Description |
|---------|-------------|
| `Where-Object` | Filter objek: `\| Where {$_.CPU -gt 10}` |
| `Select-Object` | Pilih properti: `\| Select Name, CPU` |
| `Sort-Object` | Urutkan: `\| Sort CPU -Desc` |
| `ForEach-Object` | Transformasi tiap objek: `\| ForEach {$_.Name}` |
| `Measure-Object` | Hitung, jumlah, rata-rata, min, maks |
| `Group-Object` | Kelompokkan berdasarkan nilai properti |
| `Format-Table` | Tampilkan sebagai tabel: `\| ft -Auto` |
| `Export-Csv` | Ekspor ke CSV: `\| Export-Csv out.csv` |

## File

### Operasi File

```
Get-Content log.txt                    # baca file
Set-Content out.txt "hello"            # tulis (timpa)
Add-Content out.txt "more"             # tambahkan
Get-Content log.txt | Select-String "error"  # grep
```

### Cmdlet Path & File

| Command | Description |
|---------|-------------|
| `Test-Path $path` | Periksa apakah file/direktori ada |
| `New-Item -Type File` | Buat file |
| `New-Item -Type Directory` | Buat direktori |
| `Resolve-Path` | Dapatkan path absolut |
| `Join-Path` | Gabungkan segmen path |
| `Split-Path` | Dapatkan parent atau nama file |
| `Get-ItemProperty` | Atribut dan metadata file |
| `Remove-Item -Recurse` | Hapus direktori secara rekursif |

## String

### Dasar String

```
"Hello, $name"                # interpolasi (double quotes)
'Hello, $name'                # literal (single quotes)
"Length: $($list.Count)"       # ekspresi dalam string
@"
Multi-line
here-string with $name
"@
```

### Metode String

| Command | Description |
|---------|-------------|
| `.ToUpper() / .ToLower()` | Ubah huruf besar/kecil |
| `.Trim()` | Hapus whitespace awal/akhir |
| `.Split(',')` | Pecah menjadi array |
| `.Replace('a','b')` | Ganti substring |
| `.StartsWith() / .EndsWith()` | Periksa prefix / suffix |
| `.Substring(0,5)` | Ekstrak substring |
| `.Contains('text')` | Periksa apakah mengandung |
| `-f operator` | `'{0} is {1}' -f 'sky','blue'` |

## Modul

### Manajemen Modul

```
Get-Module -ListAvailable           # modul terinstal
Find-Module -Name Az*               # cari di gallery
Install-Module -Name Pester         # instal dari gallery
Import-Module ActiveDirectory       # muat modul
```

### Perintah Modul

| Command | Description |
|---------|-------------|
| `Get-Module` | Daftar modul yang dimuat |
| `Import-Module` | Muat modul ke sesi |
| `Remove-Module` | Hapus modul dari sesi |
| `Update-Module` | Perbarui modul terinstal |
| `Get-Command -Module X` | Daftar perintah dalam modul |
| `$env:PSModulePath` | Path pencarian modul |

## Pola Umum

### Penanganan Error

```
try {
    Get-Item "C:\missing" -ErrorAction Stop
} catch {
    "Error: $_"
} finally {
    "Cleanup here"
}
```

### Execution Policy & Remoting

| Command | Description |
|---------|-------------|
| `Get-ExecutionPolicy` | Tampilkan kebijakan script saat ini |
| `Set-ExecutionPolicy RemoteSigned` | Izinkan script lokal |
| `Enter-PSSession -Computer SRV1` | Sesi remote interaktif |
| `Invoke-Command -Computer SRV1 -Script {}` | Jalankan script block dari jarak jauh |
| `Start-Job { long-task }` | Jalankan background job |
| `Receive-Job -Id 1` | Dapatkan output background job |
