Windows Server 2012 R2 / Windows 8.1 引入 PowerShell 4.0,帶來三大里程碑級更新:期望狀態配置 (DSC)、預設執行原則調整、多項實用參數增強。本文深度解析這些變化對自動化運維的實戰影響。
DSC 是 PowerShell 4.0 最大亮點,引入宣告式基礎設施即代碼範例,讓系統配置變得可版控、可重現、可審計。
# 1. 撰寫配置腳本 (Configuration)
Configuration WebServerConfig {
Node "WEB01", "WEB02" {
WindowsFeature IIS {
Ensure = "Present"
Name = "Web-Server"
}
File WebContent {
Ensure = "Present"
SourcePath = "\\FileServer\WebContent"
DestinationPath = "C:\inetpub\wwwroot"
Type = "Directory"
Recurse = $true
}
Service W3SVC {
Name = "W3SVC"
State = "Running"
StartupType = "Automatic"
}
}
}
# 2. 編譯產生 MOF
WebServerConfig -OutputPath "C:\DSC\Configs"
# 3. 推送模式:立即套用
Start-DscConfiguration -Path "C:\DSC\Configs" -Wait -Verbose
# 4. 拉取模式:節點定期從 Pull Server 獲取 MOF (需設定 LCM)
Set-DscLocalConfigurationManager -Path "C:\DSC\MetaConfig" -ComputerName WEB01
ConfigurationMode = ApplyAndAutoCorrect 自動修復。| 版本/系統 | 預設 ExecutionPolicy | 影響 |
|---|---|---|
| PowerShell 2.0/3.0 (所有系統) | Restricted | 禁止執行任何腳本,需手動 Set-ExecutionPolicy RemoteSigned 或 Bypass。 |
| PowerShell 4.0 on Windows Server 2012 R2 | RemoteSigned | 預設允許執行本地腳本 (需簽名的遠端腳本),管理員無需額外設定即可自動化。 |
| PowerShell 4.0 on Windows 8.1 | Restricted | 維持嚴格預設,保護一般用戶免受惡意腳本攻擊。 |
最佳實踐:企業環境應透過 GPO 統一設定
Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell → Turn on Script Execution=Allow local scripts and remote signed scripts(相當於 RemoteSigned),而非依賴預設值。
| 參數 | 適用 Cmdlet | 功能說明 | 實戰範例 |
|---|---|---|---|
-PipelineVariable (alias -pv) | 所有支援管線的 Cmdlet | 將管線輸出物件存入指定變數,後續管線階段可直接引用 $var,避免重複計算或傳遞複雜物件。 | Get-Process -pv procs | Where-Object CPU -gt 100 | Select-Object -First 5 -ExpandProperty Id | ForEach-Object { Stop-Process -Id $_ -WhatIf } 中 $procs 保有完整進程集合。 |
Enable-JobTrigger, Disable-JobTrigger, Register-ScheduledJob, Unregister-ScheduledJob 等 | 傳回被修改/建立的物件 (而非無輸出),利於管線串接或變數指派。 | $trigger = New-JobTrigger -Daily -At 3AM | Register-ScheduledJob -ScriptBlock {Backup-DB} -Passthru 直接取得 ScheduledJob 物件。 | |
New-JobTrigger, Set-JobTrigger (ScheduledJob 模組) | 排程工作無限期重複執行,無需指定結束時間。 | New-JobTrigger -Once -At "03:00" -RepeatIndefinitely -RepetitionInterval (New-TimeSpan -Hours 1) 每小時執行一次,永不結束。 | |
Register-ScheduledJob, Set-ScheduledJob | 註冊/修改排程工作後**立即執行一次**,無需等待下一個排程時間點。 | Register-ScheduledJob -Name "Deploy" -ScriptBlock {Deploy-App} -Trigger (New-JobTrigger -Daily -At "02:00") -RunNow 部署腳本立即跑一次,隔天 02:00 開始例行。 |
Get-Process | Where-Object CPU -gt 100 (屬性比較無需腳本區塊)。workflow),後續版本逐漸由 PowerShell 7+ / Azure Functions / Logic Apps 取代。Get-NetIPConfiguration, New-NetIPAddress, Test-NetConnection (整合 ping/traceroute/port check)。PSModulePath 目錄下模組自動載入,無需 Import-Module。RemoteSigned、無上述相容性包袱。PowerShell 4.0 奠定了現代自動化運維的宣告式基因 (DSC) 與管線程式設計便利性。理解其核心機制,能讓你在維護舊環境時遊刃有餘,也為遷移至 PowerShell 7+ / GitOps / Azure Arc 打下堅實基礎。