THAM KHẢO NHANH POWERSHELL
Cmdlets, pipeline, objects, scripting, modules
Cơ Bản
Lệnh & Trợ Giúp
Get-Help Get-Process # show help for cmdlet
Get-Help Get-Process -Online # open online docs
Get-Command *service* # find commands by name
Get-Alias ls # show alias target
Alias Phổ Biến
| ls → Get-ChildItem | Liệt kê file và thư mục |
| cd → Set-Location | Thay đổi thư mục |
| cp → Copy-Item | Sao chép file hoặc thư mục |
| mv → Move-Item | Di chuyển hoặc đổi tên |
| rm → Remove-Item | Xóa file hoặc thư mục |
| cat → Get-Content | Đọc nội dung file |
| echo → Write-Output | In ra pipeline |
| cls → Clear-Host | Xóa console |
Biến
Cơ Bản Về Biến
$name = "Alice" # string
$count = 42 # integer
$pi = 3.14 # double
$list = @(1, 2, 3) # array
$hash = @{a=1; b=2} # hashtable
Biến Tự Động
| $_ | Object pipeline hiện tại |
| $PSVersionTable | Thông tin phiên bản PowerShell |
| $HOME | Thư mục home của người dùng |
| $PWD | Thư mục hiện tại |
| $null | Giá trị null |
| $true / $false | Hằng số boolean |
| $Error | Mảng các lỗi gần đây |
| $LASTEXITCODE | Mã thoát của lệnh native cuối |
Biến Môi Trường
$env:PATH # read env var
$env:MY_VAR = "value" # set env var
Get-ChildItem Env: # list all env vars
Toán Tử
Toán Tử So Sánh
| -eq -ne | Bằng / không bằng |
| -gt -lt | Lớn hơn / nhỏ hơn |
| -ge -le | Lớn hơn/nhỏ hơn hoặc bằng |
| -like -notlike | Khớp wildcard (*, ?) |
| -match -notmatch | Khớp regex |
| -contains | Collection chứa giá trị |
| -in -notin | Giá trị thuộc/không thuộc collection |
Toán Tử Logic & Khác
| -and -or -not | Toán tử logic |
| ! | Logic NOT (alias) |
| -replace | Thay thế regex: 'hi' -replace 'h','b' |
| -split -join | Tách / nối chuỗi |
| .. | Khoảng: 1..5 → 1,2,3,4,5 |
| ?: | Ba ngôi (v7+): $x ? 'yes' : 'no' |
Luồng Điều Khiển
if / elseif / else
if ($age -ge 18) {
"Adult"
} elseif ($age -ge 13) {
"Teen"
} else {
"Child"
}
switch
switch ($color) {
"red" { "Stop" }
"green" { "Go" }
default { "Unknown" }
}
Vòng Lặp
foreach ($item in $list) { $item }
for ($i=0; $i -lt 5; $i++) { $i }
while ($x -lt 10) { $x++ }
1..5 | ForEach-Object { $_ * 2 }
Hàm
Định Nghĩa Hàm
function Get-Greeting {
param([string]$Name = "World")
"Hello, $Name!"
}
Get-Greeting -Name "Alice"
Tham Số Nâng Cao
function Copy-SafeFile {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$Dest
)
Copy-Item $Path $Dest -WhatIf:$WhatIfPreference
}
Objects & Pipeline
Cơ Bản 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
Cmdlets Pipeline Quan Trọng
| Where-Object | Lọc objects: | Where {$_.CPU -gt 10} |
| Select-Object | Chọn properties: | Select Name, CPU |
| Sort-Object | Sắp xếp: | Sort CPU -Desc |
| ForEach-Object | Biến đổi mỗi: | ForEach {$_.Name} |
| Measure-Object | Đếm, tổng, trung bình, min, max |
| Group-Object | Nhóm theo giá trị property |
| Format-Table | Hiển thị dạng bảng: | ft -Auto |
| Export-Csv | Xuất ra CSV: | Export-Csv out.csv |
Files
Thao Tác File
Get-Content log.txt # read file
Set-Content out.txt "hello" # write (overwrite)
Add-Content out.txt "more" # append
Get-Content log.txt | Select-String "error" # grep
Cmdlets Path & File
| Test-Path $path | Kiểm tra file/thư mục tồn tại |
| New-Item -Type File | Tạo file |
| New-Item -Type Directory | Tạo thư mục |
| Resolve-Path | Lấy đường dẫn tuyệt đối |
| Join-Path | Kết hợp các phần đường dẫn |
| Split-Path | Lấy phần cha hoặc lá |
| Get-ItemProperty | Thuộc tính và metadata file |
| Remove-Item -Recurse | Xóa thư mục đệ quy |
Strings
Cơ Bản String
"Hello, $name" # interpolation (double quotes)
'Hello, $name' # literal (single quotes)
"Length: $($list.Count)" # expression in string
@"
Multi-line
here-string with $name
"@
Phương Thức String
| .ToUpper() / .ToLower() | Chuyển đổi hoa/thường |
| .Trim() | Xóa khoảng trắng đầu/cuối |
| .Split(',') | Tách thành mảng |
| .Replace('a','b') | Thay thế chuỗi con |
| .StartsWith() / .EndsWith() | Kiểm tra prefix / suffix |
| .Substring(0,5) | Trích xuất chuỗi con |
| .Contains('text') | Kiểm tra có chứa không |
| -f operator | '{0} is {1}' -f 'sky','blue' |
Modules
Quản Lý Module
Get-Module -ListAvailable # installed modules
Find-Module -Name Az* # search gallery
Install-Module -Name Pester # install from gallery
Import-Module ActiveDirectory # load module
Lệnh Module
| Get-Module | Liệt kê các modules đã tải |
| Import-Module | Tải module vào session |
| Remove-Module | Gỡ module khỏi session |
| Update-Module | Cập nhật module đã cài |
| Get-Command -Module X | Liệt kê lệnh trong module |
| $env:PSModulePath | Đường dẫn tìm kiếm module |
Mẫu Phổ Biến
Xử Lý Lỗi
try {
Get-Item "C:\missing" -ErrorAction Stop
} catch {
"Error: $_"
} finally {
"Cleanup here"
}
Execution Policy & Remoting
| Get-ExecutionPolicy | Hiển thị chính sách script hiện tại |
| Set-ExecutionPolicy RemoteSigned | Cho phép script nội bộ |
| Enter-PSSession -Computer SRV1 | Session remote tương tác |
| Invoke-Command -Computer SRV1 -Script {} | Chạy script block từ xa |
| Start-Job { long-task } | Chạy job nền |
| Receive-Job -Id 1 | Lấy đầu ra job nền |