先決條件
本章所示的一些範例需要 SqlServer PowerShell 模組。 如需 SqlServer PowerShell 模組和安裝指示的詳細資訊,請參閱 sql Server PowerShell 概觀。 它也會在後續章節中使用。 在您的 Windows 實驗室環境電腦上下載並安裝它。
右對齊格式
在第 4 章中,您已學會盡可能向左篩選。 手動格式化命令的輸出規則與該規則類似,不同之處在於結果必須盡可能靠右顯示。
最常見的格式命令是 Format-Table 與 Format-List。 也可以使用 Format-Wide 和 Format-Custom,但較不常見。
如第 3 章所述,命令如果返回超過四個屬性,預設將是清單格式,除非使用自定義格式。
Get-Service -Name w32time |
Select-Object -Property Status, DisplayName, Can*
Status : Running
DisplayName : Windows Time
CanPauseAndContinue : False
CanShutdown : True
CanStop : True
使用 Format-Table Cmdlet 手動覆寫格式,以表格形式顯示輸出,而不是清單。
Get-Service -Name w32time |
Select-Object -Property Status, DisplayName, Can* |
Format-Table
Status DisplayName CanPauseAndContinue CanShutdown CanStop
------ ----------- ------------------- ----------- -------
Running Windows Time False True True
Get-Service 的預設輸出是數據表中的三個屬性。
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
使用 Format-List cmdlet 來覆寫預設格式,並以清單形式返回結果。
Get-Service -Name w32time | Format-List
請注意,將 Get-Service 簡單傳送到 Format-List 會使其返回其他的屬性。 這並非會發生在每一個命令上,而是由於每個命令背後的格式設定方式不同。
Name : w32time
DisplayName : Windows Time
Status : Running
DependentServices : {}
ServicesDependedOn : {}
CanPauseAndContinue : False
CanShutdown : True
CanStop : True
ServiceType : Win32OwnProcess, Win32ShareProcess
使用格式 Cmdlet 時,首要知道的是,它們會產生與 PowerShell 中標準物件不同的格式物件。
Get-Service -Name w32time | Format-List | Get-Member
TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Obj...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
autosizeInfo Property Microsoft.PowerShell.C...
ClassId2e4f51ef21dd47e99d3c952918aff9cd Property string ClassId2e4f51ef...
groupingEntry Property Microsoft.PowerShell.C...
pageFooterEntry Property Microsoft.PowerShell.C...
pageHeaderEntry Property Microsoft.PowerShell.C...
shapeInfo Property Microsoft.PowerShell.C...
TypeName: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Obj...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
ClassId2e4f51ef21dd47e99d3c952918aff9cd Property string ClassId2e4f51ef...
groupingEntry Property Microsoft.PowerShell.C...
shapeInfo Property Microsoft.PowerShell.C...
TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Obj...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
ClassId2e4f51ef21dd47e99d3c952918aff9cd Property string ClassId2e4f51ef...
formatEntryInfo Property Microsoft.PowerShell.C...
outOfBand Property bool outOfBand {get;set;}
writeStream Property Microsoft.PowerShell.C...
TypeName: Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Obj...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
ClassId2e4f51ef21dd47e99d3c952918aff9cd Property string ClassId2e4f51ef...
groupingEntry Property Microsoft.PowerShell.C...
TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Obj...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
ClassId2e4f51ef21dd47e99d3c952918aff9cd Property string ClassId2e4f51ef...
groupingEntry Property Microsoft.PowerShell.C...
這表示格式命令無法傳送至大多數的其他命令。 它們可以管線傳送至某些 Out-* 命令,但僅止於此。 這就是為什麼您想要在行尾處執行任何格式設定(格式右)。
別名
PowerShell 中的別名是命令的較短名稱。 PowerShell 包含一組內建別名,您也可以定義自己的別名。
Get-Alias Cmdlet 可用來尋找別名。 如果您已經知道命令的別名,則會使用 Name 參數來判斷別名相關聯的命令。
Get-Alias -Name gcm
CommandType Name Version
----------- ---- -------
Alias gcm -> Get-Command
您可以為 Name 參數的值指定多個別名。
Get-Alias -Name gcm, gm
CommandType Name Version
----------- ---- -------
Alias gcm -> Get-Command
Alias gm -> Get-Member
您通常會看到省略 Name 參數,因為它是位置參數。
Get-Alias gm
CommandType Name Version
----------- ---- -------
Alias gm -> Get-Member
如果您想要尋找命令的別名,則必須使用 Definition 參數。
Get-Alias -Definition Get-Command, Get-Member
CommandType Name Version
----------- ---- -------
Alias gcm -> Get-Command
Alias gm -> Get-Member
Definition 參數不能以位置方式使用,因此必須明確指定。
別名可以為您節省一些按鍵,而且當您在控制台中輸入命令時,它們運作得很好。 它們不應該用於文稿或任何您要儲存或與其他人共用的程式代碼中。 如本書稍早所述,用完整的 Cmdlet 和參數名稱來進行自我説明,讓內容更容易理解。
建立自己的別名時請小心,因為它們只存在於您電腦上的目前PowerShell工作階段中。
供應商
PowerShell 中的提供者是允許類似文件系統存取方式來訪問資料存放區的介面。 PowerShell 中有數個內建提供者。
Get-PSProvider
如下列結果所示,登錄、別名、環境變數、文件系統、函式、變數、憑證和 WSMan 都有內建提供者。
Name Capabilities Drives
---- ------------ ------
Registry ShouldProcess, Transactions {HKLM, HKCU}
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Cr... {C, D}
Function ShouldProcess {Function}
Variable ShouldProcess {Variable}
這些提供者用來公開數據存放區的實際磁碟驅動器,可以使用 Get-PSDrive Cmdlet 來判斷。
Get-PSDrive Cmdlet 不僅會顯示提供者公開的磁碟,還會顯示 Windows 邏輯磁碟,包括對應至網路共用的磁碟。
Get-PSDrive
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
Alias Alias
C 18.56 107.62 FileSystem C:\
Cert Certificate \
D FileSystem D:\
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan
第三方模組,例如 ActiveDirectory PowerShell 模組和 SqlServer PowerShell 模組,都會新增自己的 PowerShell 提供者和 PSDrive。
匯入 ActiveDirectory 和 SqlServer PowerShell 模組。
Import-Module -Name ActiveDirectory, SQLServer
檢查是否已新增任何其他 PowerShell 提供者。
Get-PSProvider
請注意,在下列結果集中,現在有兩個新的 PowerShell 提供者存在,一個用於 Active Directory,另一個用於 SQL Server。
Name Capabilities Drives
---- ------------ ------
Registry ShouldProcess, Transactions {HKLM, HKCU}
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Credentials {C, A, D}
Function ShouldProcess {Function}
Variable ShouldProcess {Variable}
ActiveDirectory Include, Exclude, Filter, Shoul... {AD}
SqlServer Credentials {SQLSERVER}
已經為每個模組新增了 PSDrive。
Get-PSDrive
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
A FileSystem A:\
AD ActiveDire... //RootDSE/
Alias Alias
C 19.38 107.13 FileSystem C:\
Cert Certificate \
D FileSystem D:\
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
SQLSERVER SqlServer SQLSERVER:\
Variable Variable
WSMan WSMan
PSDrive 可以像傳統的文件系統一樣存取。
Get-ChildItem -Path Cert:\LocalMachine\CA
PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\CA
Thumbprint Subject
---------- -------
FEE449EE0E3965A5246F000E87FDE2A065FD89D4 CN=Root Agency
D559A586669B08F46A30A133F8A9ED3D038E2EA8 OU=www.verisign.com/CPS Incorp....
109F1CAED645BB78B3EA2B94C0697C740733031C CN=Microsoft Windows Hardware C...
比較運算子
PowerShell 包含各種比較運算符,可用來比較值或尋找符合特定模式的值。 下表包含PowerShell中的比較運算子清單。
表格中列出的所有運算子都不區分大小寫。 若要區分大小寫,請將 c 放在運算符前面。 例如,-ceq 是等於 (-eq) 比較運算符的區分大小寫版本。
| 操作員 | 定義 |
|---|---|
-eq |
等於 |
-ne |
不等於 |
-gt |
大於 |
-ge |
大於或等於 |
-lt |
小於 |
-le |
小於或等於 |
-like |
使用 * 通配符字元進行比對 |
-notlike |
不符合使用 * 通配符字符 |
-match |
符合指定的正則表達式 |
-notmatch |
不符合指定的正則表達式 |
-contains |
判斷集合是否包含指定的值 |
-notcontains |
判斷集合是否不包含特定值 |
-in |
判斷指定的值是否在集合中 |
-notin |
判斷指定的值是否不在集合中 |
-replace |
取代指定的值 |
正確使用大小寫的「PowerShell」等於小寫的「powershell」,這是使用 equals 比較運算子比較得出的結果。
'PowerShell' -eq 'powershell'
True
使用區分大小寫的相等比較運算子時,結果不是相等的。
'PowerShell' -ceq 'powershell'
False
不等於的比較運算符號會反轉條件。
'PowerShell' -ne 'powershell'
False
大於、大於或等於、小於和小於或等於運算子皆可用於字串或數值。
5 -gt 5
False
使用大於或等於取代先前範例中的大於,會傳回布林值 true,因為五等於五。
5 -ge 5
True
根據前兩個範例的結果,您可能會推測小於或小於等於如何運作。
5 -lt 10
True
-like 和 -match 運算符可能會造成混淆,即使是有經驗的 PowerShell 使用者也是如此。
-like 會與通配符 * 和 ? 搭配使用來執行「like」相符比對。
'PowerShell' -like '*shell'
True
-match 運算符會使用正則表達式來執行比對。
'PowerShell' -match '^.*shell$'
True
使用範圍運算子,將數位 1 到 10 儲存在變數中。
$Numbers = 1..10
判斷 $Numbers 變數是否包含15。
$Numbers -contains 15
False
判斷它是否包含數位 10。
$Numbers -contains 10
True
-notcontains 運算符會反轉邏輯,以查看 $Numbers 變數是否不包含值。
$Numbers -notcontains 15
上一個範例會傳回 布爾值 true,因為 $Numbers 變數確實不包含 15。
True
不過,它確實包含數字 10,因此在測試時為 false。
$Numbers -notcontains 10
False
-in 比較運算符首次在PowerShell 3.0版中引進。 它用來判斷 陣列中的值是否 $Numbers 變數是陣列,因為它承載多個值。
15 -in $Numbers
False
換句話說,-in 執行與 包含比較運算符相同的測試,但方向相反。
10 -in $Numbers
True
15 不在 $Numbers 陣列中,因此會在下列範例中傳回 false。
15 -in $Numbers
False
就像 -contains 運算符一樣,not 反轉 -in 運算子的邏輯。
10 -notin $Numbers
上一個範例會傳回 false,因為 $Numbers 陣列包含 10,而且條件測試會判斷它是否不包含 10。
False
判斷 15 是否不在 $Numbers 陣列中。
15 -notin $Numbers
15是「不在」$Numbers 陣列中,因此它會傳回 布爾值 true。
True
運算子 -replace 做的正是您所想的。 它用來取代某物。 指定一個值將用空值取代該值。 在下列範例中,您將 “Shell” 取代為空白。
'PowerShell' -replace 'Shell'
Power
如果您想要以不同的值取代值,請在您想要取代的模式之後指定新的值。 我每年都會嘗試在巴頓魯日的 SQL Saturday 上發表演講。 在下列範例中,“Saturday” 一詞會取代為縮寫 “Sat”。
'SQL Saturday - Baton Rouge' -replace 'saturday','Sat'
SQL Sat - Baton Rouge
還有一些方法,例如 Replace(),可以用來以類似替換運算子的方式進行替換。 不過,根據預設,-replace 運算符不區分大小寫,且 Replace() 方法會區分大小寫。
'SQL Saturday - Baton Rouge'.Replace('saturday','Sat')
請注意,這個字「Saturday」不會被取代。 這是因為它是在與原始情況不同的情況下指定的。
SQL Saturday - Baton Rouge
當「Saturday」一詞在與原始案例相同的情況下指定時,Replace() 方法會如預期般地進行取代。
'SQL Saturday - Baton Rouge'.Replace('Saturday','Sat')
SQL Sat - Baton Rouge
使用方法來轉換數據時請小心,因為您可能會遇到無法預見的問題,例如失敗 土耳其測試。 如需範例,請參閱我的部落格文章,使用 Pester 測試 PowerShell 程式代碼與其他文化特性。 我建議盡可能使用運算符,而不是方法,以避免這類問題。
雖然可以使用比較運算符,如先前範例所示,我通常會使用它們搭配 Where-Object Cmdlet 來執行篩選。
總結
您在本章學習了幾個主題,包括正確格式化、別名、供應商和比較運算子。
回顧
- 為什麼必須盡可能向右進行格式化?
- 如何判斷
%別名對應的實際 cmdlet 是什麼? - 為什麼您不應該在儲存的腳本中使用別名,或與您其他人共用的程序代碼?
- 在與註冊表提供者相關聯的磁碟驅動器上執行目錄列出操作。
- 使用 replace 運算子而非 replace 方法,有什麼主要優點?
引用
後續步驟
在下一章中,您將瞭解流程控制、腳本、迴圈和條件式邏輯。