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-ChildItemLiệt kê file và thư mục
cd → Set-LocationThay đổi thư mục
cp → Copy-ItemSao chép file hoặc thư mục
mv → Move-ItemDi chuyển hoặc đổi tên
rm → Remove-ItemXóa file hoặc thư mục
cat → Get-ContentĐọc nội dung file
echo → Write-OutputIn ra pipeline
cls → Clear-HostXó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
$PSVersionTableThông tin phiên bản PowerShell
$HOMEThư mục home của người dùng
$PWDThư mục hiện tại
$nullGiá trị null
$true / $falseHằng số boolean
$ErrorMảng các lỗi gần đây
$LASTEXITCODEMã 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 -neBằng / không bằng
-gt -ltLớn hơn / nhỏ hơn
-ge -leLớn hơn/nhỏ hơn hoặc bằng
-like -notlikeKhớp wildcard (*, ?)
-match -notmatchKhớp regex
-containsCollection chứa giá trị
-in -notinGiá trị thuộc/không thuộc collection
Toán Tử Logic & Khác
-and -or -notToán tử logic
!Logic NOT (alias)
-replaceThay thế regex: 'hi' -replace 'h','b'
-split -joinTá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-ObjectLọc objects: | Where {$_.CPU -gt 10}
Select-ObjectChọn properties: | Select Name, CPU
Sort-ObjectSắp xếp: | Sort CPU -Desc
ForEach-ObjectBiến đổi mỗi: | ForEach {$_.Name}
Measure-ObjectĐếm, tổng, trung bình, min, max
Group-ObjectNhóm theo giá trị property
Format-TableHiển thị dạng bảng: | ft -Auto
Export-CsvXuấ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 $pathKiểm tra file/thư mục tồn tại
New-Item -Type FileTạo file
New-Item -Type DirectoryTạo thư mục
Resolve-PathLấy đường dẫn tuyệt đối
Join-PathKết hợp các phần đường dẫn
Split-PathLấy phần cha hoặc lá
Get-ItemPropertyThuộc tính và metadata file
Remove-Item -RecurseXó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-ModuleLiệt kê các modules đã tải
Import-ModuleTải module vào session
Remove-ModuleGỡ module khỏi session
Update-ModuleCập nhật module đã cài
Get-Command -Module XLiệ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-ExecutionPolicyHiển thị chính sách script hiện tại
Set-ExecutionPolicy RemoteSignedCho phép script nội bộ
Enter-PSSession -Computer SRV1Session 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 1Lấy đầu ra job nền