從管線中移除物件 (Where-Object)Removing Objects from the Pipeline (Where-Object)

在 PowerShell 中,您通常會產生並沿著管線傳遞比所需更多的物件。In PowerShell, you often generate and pass along more objects to a pipeline than you want. 您可以使用 Format-* Cmdlet 來指定要顯示的特定物件屬性,但這樣做並無法解決從顯示中移除整個物件的問題。You can specify the properties of particular objects to display by using the Format-* cmdlets, but this does not help with the problem of removing entire objects from the display. 您可能需要在結束管線之前篩選物件,以便只對初始產生的物件子集執行動作。You may want to filter objects before the end of a pipeline, so you can perform actions on only a subset of the initially-generated objects.

PowerShell 包含了 Where-Object Cmdlet,可讓您測試管線中的每個物件,並只在符合特定測試條件時才沿著管線傳遞。PowerShell includes a Where-Object cmdlet that allows you to test each object in the pipeline and only pass it along the pipeline if it meets a particular test condition. 未通過測試的物件會從管線中移除。Objects that do not pass the test are removed from the pipeline. 您需提供測試條件作為 FilterScript 參數的值。You supply the test condition as the value of the FilterScript parameter.

使用 Where-Object 執行簡單的測試Performing Simple Tests with Where-Object

FilterScript 的值是評估為 true 或 false 的「指令碼區塊」 (以大括弧 {} 括住的一或多個 PowerShell 命令)。The value of FilterScript is a script block - one or more PowerShell commands surrounded by braces ({}) - that evaluates to true or false. 這些指令碼區塊可以很簡單,但若要建立它們,需要了解另一個 PowerShell 概念:比較運算子。These script blocks can be very simple, but creating them requires knowing about another PowerShell concept, comparison operators. 比較運算子會比較出現在運算子兩側的項目。A comparison operator compares the items that appear on each side of it. 比較運算子是以連字號字元 (-) 開頭,後面接著名稱。Comparison operators begin with a hyphen character (-) and are followed by a name. 基本比較運算子適用於幾乎任何類型的物件。Basic comparison operators work on almost any kind of object. 更進階的比較運算子只適用於文字或陣列。The more advanced comparison operators might only work on text or arrays.

注意

根據預設,搭配文字使用時,PowerShell 比較運算子不區分大小寫。By default, when working with text, PowerShell comparison operators are case-insensitive.

基於剖析考量,不會使用 <>= 等符號作為比較運算子。Due to parsing considerations, symbols such as <,>, and = are not used as comparison operators. 相反地,比較運算子是由字母所組成。Instead, comparison operators are comprised of letters. 下表列出基本比較運算子。The basic comparison operators are listed in the following table.

比較運算子Comparison Operator 意義Meaning 範例 (傳回 true)Example (returns true)
-eq-eq 等於is equal to 1 -eq 11 -eq 1
-ne-ne 不等於Is not equal to 1 -ne 21 -ne 2
-lt-lt 小於Is less than 1 -lt 21 -lt 2
-le-le 小於或等於Is less than or equal to 1 -le 21 -le 2
-gt-gt 大於Is greater than 2 -gt 12 -gt 1
-ge-ge 大於或等於Is greater than or equal to 2 -ge 12 -ge 1
-like-like 像是 (文字的萬用字元比較)Is like (wildcard comparison for text) "file.doc" -like "f*.do?""file.doc" -like "f*.do?"
-notlike-notlike 不像是 (文字的萬用字元比較)Is not like (wildcard comparison for text) "file.doc" -notlike "p*.doc""file.doc" -notlike "p*.doc"
-contains-contains 包含Contains 1,2,3 -contains 11,2,3 -contains 1
-notcontains-notcontains 不包含Does not contain 1,2,3 -notcontains 41,2,3 -notcontains 4

Where-Object 指令碼區塊使用特殊變數 $_ 來參照管線中目前的物件。Where-Object script blocks use the special variable $_ to refer to the current object in the pipeline. 以下示範其運作方式。Here is an example of how it works. 如果您有一份數字清單,而且只想要傳回小於 3 的數字,您可以輸入下列命令以使用 Where-Object 來篩選數字︰If you have a list of numbers, and only want to return the ones that are less than 3, you can use Where-Object to filter the numbers by typing:

1,2,3,4 | Where-Object {$_ -lt 3}
1
2

根據物件屬性篩選Filtering Based on Object Properties

因為 $_ 參照了目前的管線物件,所以我們可以針對測試來存取其屬性。Since $_ refers to the current pipeline object, we can access its properties for our tests.

舉例來說,我們可以檢視 WMI 中的 Win32_SystemDriver 類別。As an example, we can look at the Win32_SystemDriver class in WMI. 一部系統上可能會有數百個系統驅動程式,但您可能只對某一組系統驅動程式感興趣,例如目前執行中的驅動程式。There might be hundreds of system drivers on a particular system, but you might only be interested in a particular set of the system drivers, such as those which are currently running. 針對 Win32_SystemDriver 類別,相關屬性為 StateFor the Win32_SystemDriver class the relevant property is State. 您可以輸入下列命令來篩選系統驅動程式,只選取執行中的驅動程式︰You can filter the system drivers, selecting only the running ones by typing:

Get-CimInstance -Class Win32_SystemDriver |
  Where-Object {$_.State -eq 'Running'}

這仍會產生一長串清單。This still produces a long list. 您可以一併測試 StartMode 值,以篩選成只選取設定為自動啟動的驅動程式:You may want to filter to only select the drivers set to start automatically by testing the StartMode value as well:

Get-CimInstance -Class Win32_SystemDriver |
  Where-Object {$_.State -eq "Running"} |
    Where-Object {$_.StartMode -eq "Auto"}
DisplayName : RAS Asynchronous Media Driver
Name        : AsyncMac
State       : Running
Status      : OK
Started     : True

DisplayName : Audio Stub Driver
Name        : audstub
State       : Running
Status      : OK
Started     : True
...

因為我們知道驅動程式正在執行,所以這會提供許多不再需要的資訊。This gives us a lot of information we no longer need because we know that the drivers are running. 事實上,我們此時可能只需要名稱和顯示名稱資訊。In fact, the only information we probably need at this point are the name and the display name. 下列命令只會包含這兩個屬性,以產生更簡單的輸出︰The following command includes only those two properties, resulting in much simpler output:

Get-CimInstance -Class Win32_SystemDriver |
  Where-Object {$_.State -eq "Running"} |
    Where-Object {$_.StartMode -eq "Manual"} |
      Format-Table -Property Name,DisplayName
Name              DisplayName
----              -----------
AsyncMac               RAS Asynchronous Media Driver
bindflt                Windows Bind Filter Driver
bowser                 Browser
CompositeBus           Composite Bus Enumerator Driver
condrv                 Console Driver
HdAudAddService        Microsoft 1.1 UAA Function Driver for High Definition Audio Service
HDAudBus               Microsoft UAA Bus Driver for High Definition Audio
HidUsb                 Microsoft HID Class Driver
HTTP                   HTTP Service
igfx                   igfx
IntcDAud               Intel(R) Display Audio
intelppm               Intel Processor Driver
...

上述命令中有兩個 Where-Object 元素,但可使用 -and 邏輯運算子以單一 Where-Object 元素來表示它們,就像這樣︰There are two Where-Object elements in the above command, but they can be expressed in a single Where-Object element by using the -and logical operator, like this:

Get-CimInstance -Class Win32_SystemDriver |
  Where-Object {($_.State -eq 'Running') -and ($_.StartMode -eq 'Manual')} |
    Format-Table -Property Name,DisplayName

下表列出標準邏輯運算子。The standard logical operators are listed in the following table.

邏輯運算子Logical Operator 意義Meaning 範例 (傳回 true)Example (returns true)
-and-and 邏輯 and;若兩側為 true 即為 trueLogical and; true if both sides are true (1 -eq 1) -and (2 -eq 2)(1 -eq 1) -and (2 -eq 2)
-or-or 邏輯 or;若任一側為 true 即為 trueLogical or; true if either side is true (1 -eq 1) -or (1 -eq 2)(1 -eq 1) -or (1 -eq 2)
-not-not 邏輯 not;將 true 與 false 反轉Logical not; reverses true and false -not (1 -eq 2)-not (1 -eq 2)
! 邏輯 not;將 true 與 false 反轉Logical not; reverses true and false !(1 -eq 2)!(1 -eq 2)