標籤:
Learn Windows PowerShell 3 in a Month of Lunches(2rd)2013, DON JONES
這本書基於 PowerShell 3.0,做初學者教材甚好,若有 Linux shell 基礎則可一目十行。如下便是摘錄式筆記,僅記錄一些感興趣的重點,涉及大部分章節。
書中很少涉及文法,因為按作者的說法:操起命令直接上,這才是 PS 的主要使用模式(PowerShell-ish ways),而非一般的指令碼編程,流控之類的文法都只是命令的粘合劑。
讀完一遍,對 PS 突出印象:
- 現代化的、風格一致的設計
應該借鑒了 Linux shell、python、C# 等;一致性降低了學習使用成本
- 物件導向、基於 .NET 架構
一切皆對象,消除了無結構文本的弊端;可以直接使用 .NET 對象,功能真強
- 命令式
開發迭代模型:run—result—modify—retry
ch2. Meet PowerShell(初識 PS)
PowerShell 包含兩個組件:
- PS console
輕快,不支援雙位元組字元集,無補全
- PS ISE (integrated scripting environment)
基於 WPF,支援中文,強大的協助與補全
查看版本號碼: $PSVersionTable
ch3. Using the help system(協助系統)
媲美 GUI 的 CLI 協助系統:能迅速找到命令並瞭解其用法(支援萬用字元)
- Get-Command 尋找匹配的命令
- Get-Help 查看命令用法
- Get-Member 查看對象的類型和成員
- Help 是 function,相當於 Get-Help | More
查看樣本:Help Get-EventLog -example
詳細資料:Help -full
- Show-command 帶 GUI 協助的填寫
4 種命令 Command:cmdlet(命名規範 verbs+nouns),function,workflow,externApp。例: Get-Service -name e,s*
協助系統先升級:update-help(-Source 可指定本地更新源)
多個參數搭配路徑
ch4. Running commands(命令)
cmdlet:原生命令,為 .Net 語言編寫
- 可選 optional 參數整個在方括弧裡
[-ComputerName <string[]>],這裡的數組用逗號分隔的列表表示;用參數縮寫時能唯一標識即可,如 -comp
- 否則為強制 mandatory 參數,
[-LogName] <string>
- 若參數名稱也在方括弧裡,則為位置 positional 參數
externApp(外部命令,但應優先用 cmdlet)
$exe = “C:\mount.exe”
$host = “srv”
$user = “nick”
& $exe -h $host -u $user
新寫法:-- C:\mount.exe -h srv -u nick,會直接傳給 cmd,不解析
ch5. Working with providers
PSProvider 適配器,以類檔案系統的方式,來導航與管理資料存放區(動態結構),如註冊表。查看可用:Get-PSProvider
相關 cmdlet 的 noun 常帶 “Item”(指單獨對象,如檔案)
ItemProperty 表示 item 屬性,如唯讀,一般都有 -Path 屬性,支援萬用字元;ChildItem 指子物件
ch6. The pipeline: connecting commands(Pipeline)ch7. Adding commands(PS 擴充機制)
兩種:module 和 snap-in(dll+xml)
get-pssnapin -registered 註冊
add-pssnapin sqlservercmdletsnapin100,sqlserverprovidersnapin100
Get-Command -pssnapin sqlservercmdletsnapin100
module 不用註冊,根據 $PSModulePath 自動探索,按需載入
get-command -Module DnsClient
有些特定的管理 shell 其實是帶參數啟動 powershell.exe -noexit -command import-module ActiveDirectory
ch8. Objects: data by another name(對象)
查看:get-process | get-member
a collection of objects as a big in-memory table ofinformation, with propertiesas the columns and individual objects the rows.
PS 對象一般來自 .net 架構,但 ETS(Extensible Type System)會添加些額外屬性(ScriptProperty,NoteProperty,AliasProperty)以利使用。
對象的 property 用的很多,但 action/method 很少用,因為通常由 cmdlet 實現
Get-Process | Sort-Object VM,ID -desc
Get-Process | Select-Object Name,ID,VM,PM
Select-Objectis 用來選擇或建立 properties(會產生新對象), 以及特定行,-expandProperty 可以擷取值列表. 而 Where-Object 根據指定條件刪除或過濾 pipeline 裡的 objects。
pipeline 的每一步都可能產生不同對象,所以要用 gm 來確定
ch9. The pipeline,deeper(深入 pipeline)
Pipeline parameter binding:
Try1. ByValue:把輸入與參數類型進行匹配;參數需支援pipelineInputByValue(可通過 Help -full 查看);僅能匹配一個參數(能否手動指定?)
Try2. ByPropertyName:僅名字匹配;需支援pipInByPropertyName;多參數匹配
圓括弧命令用法:
Get-WmiObject -class Win32_BIOS -ComputerName (Get-Content .\comput
ers.txt)
ch10. Formatting—and why it’s done on the right(格式化)ch11. Filtering and comparisons(過濾與比較)
- Filter left (命令需支援 -filter 參數)
- Where-Object(使用類似的比較符)
Get-Service | Where { $_.Status -eq ‘Running‘ } --> Get-Service | Where Status -eq ‘Running‘(單條件可化簡)
(5 -gt 10) -and (10 -gt 100)
$_.Responding -eq $False
ch12. A practical interlude(實踐)
- 需求:remove all print jobs from a local printer “Accounting” every 3 a.m.
- 尋找命令
help *task*;get-command -module scheduledtasks
- 學慣用法
help new-scheduledtask -full
ch13. Remote control: one to one, and one to manych14. Using Windows Management Instrumentation(WMI)
WMI 能夠擷取大量系統資訊,但不好用(缺乏統一規劃,文檔缺乏)。對 PS 來說只是個可以借用的外部技術,建議使用 CIM 封裝命令與之互動
wmi 必知必會
repository
— namespace 例如 root\CIMv2 就包含了所有系統和硬體資訊
— class 代表管理組件,一個執行個體對應一個現實組件
軟體:wmi explorer
- Get-WmiObject(retrieve all instances of that class from the computer specified,legacy!) + Invoke-WmiMethod
查看 Get-WmiObject -Namespace root\CIMv2 -list | where name -like ‘dis‘
gwmi -class win32_desktop -filter “name=’COMPANY\Administrator’”
- Get-CimInstance + Invoke-CimMethod
查看 Get-CimClass -Namespace root\CIMv2
Get-CimInstance -ClassName Win32_LogicalDisk
ch15. Multitasking with background jobs(後台多任務)
Help * -parameter asjob
ch16. Working with many objects, one at a time(大量操作)
大量操作的三種方法:batch cmdlets, WMImethods, and object enumeration.
- Get-Service -name BITS,Spooler,W32Time -computer Server1,Server2,Server3 | Set-Service -passthru -startuptype Automatic
Stop-Service -name *B*
缺點是批量處理時一般沒有輸出,此時可以使用 -passThru 來查看被處理的輸入
- gwmi win32_networkadapterconfiguration -filter “description like ‘%intel%’” | Invoke-WmiMethod -name EnableDHCP
會輸出一個 result object,可以看到每個操作的 ReturnValue,但無法分辨
- gwmi win32service -filter “name = ‘BITS’” | foreach-object {$.change($null,$null,$null,$null,$null,$null,$null,”[email protected]”) }
ch17. Security alertch18. Variables: a place to store your stuff(變數)
一切皆對象
${My Variable} = ‘SERVER-R2’,’SERVER1’,’localhost’
[int]$number = Read-Host “Enter a number”(型別宣告)
‘$‘ is a cue to the shell that what follows is going to be a variable name, and that we want to access the contents of that variable.
能夠存放多個不同類型的對象
單引號 — a literal string
雙引號 — expansion string,但僅在初始解析時替換!
轉義符 — ˜
subexpression — $(cmd) ==> string
ch19. Input and outputch20. Sessions: remote control with less work
長串連
$iis_servers = new-pssession -comp web1,web2,web3
- Using sessions with Enter-PSSession(interactive)
- Using sessions with Invoke-Command
invoke-command -command { get-wmiobject -class win32_process } -session (get-pssession -comp loc*)
- Disconnect & Reconnect session
ch21. You call this scripting?
如何寫 help 文檔
One script, one pipeline
within a script, you only have one pipeline to work with.Normally, your scripts should strive to only output one kind of object, so that PowerShell can produce sensible text output.
ch22. Improving your parameterized script(命令列選項)ch23. Advanced remoting configurationch24. Using regular expressions to parse text filesch25. Additional random tips, tricks, and techniquesch26. Using someone else’s scriptch27. Never the end
進階學習:
- PowerShell’s simplified scripting language
- Scope
- Functions, and the ability to build multiple tools into a single script file
- Error handling
- Writing help
- Debugging
- Custom formatting views
- Custom type extensions
- Script and manifest modules
- Using databases
- Workflows
- Pipeline troubleshooting
- Complex object hierarchies
- Globalization and localization
- GUI-based PowerShell tools
- Proxy functions
- Constrained remoting and delegated administration
- Using .NET
Windows Powershell 3 極速入門