about_Comparison_Operators

简短说明

PowerShell 中的比较运算符可以将集合的两个值或筛选器元素与输入值进行比较。

长说明

使用比较运算符可以比较与指定模式匹配的值或查找值。 PowerShell 包含以下比较运算符:

等式

  • -eq-ieq-ceq - 等于
  • -ne-ine-cne - 不等于
  • -gt-igt-cgt - 大于
  • -ge-ige-cge - 大于或等于
  • -lt-ilt-clt - 小于
  • -le-ile-cle - 小于或等于

匹配

  • -like-ilike-clike - 字符串匹配通配符模式
  • -notlike-inotlike-cnotlike - 字符串与通配符模式不匹配
  • -match-imatch-cmatch - 字符串匹配正则表达式模式
  • -notmatch-inotmatch-cnotmatch - 字符串与正则表达式模式不匹配

替代功能

  • -replace-ireplace-creplace - 替换与正则表达式模式匹配的字符串

包含

  • -contains-icontains-ccontains - 集合包含值
  • -notcontains-inotcontains-cnotcontains - 集合不包含值
  • -in - 值位于集合中
  • -notin - 值不在集合中

类型

  • -is - 这两个对象的类型相同
  • -isnot - 对象类型不相同

常用功能

除非使用显式区分大小写的运算符,否则字符串比较不区分大小写。 若要使比较运算符区分大小写,请在 - 后添加 c。 例如,-ceq 是区分大小写的 -eq 版本。 若要显式区分大小写,请在 - 后添加 i。 例如,-ieq-eq 的显式不区分大小写的版本。

字符串比较使用 InvariantCulture 进行区分大小写和不区分大小写的比较。 这是 unicode 码位之间的比较,勿使用特定于区域性的排序规则进行排序。 无论当前是何区域性,结果是相同的。

运算符的输入为 标量 值时,运算符返回 布尔 值。 当输入是集合时,运算符返回与表达式右侧值匹配的集合的元素。 如果集合中没有匹配项,比较运算符将返回空数组。 例如:

$a = (1, 2) -eq 3
$a.GetType().Name
$a.Count
Object[]
0

有几个例外情况:

  • 包含和类型运算符始终返回布尔
  • -replace 运算符返回替换结果
  • 除非表达式左侧是集合,否则 -match-notmatch 运算符还会填充 $Matches 自动变量。

相等运算符

-eq 和 -ne

当左侧为标量时,如果右侧等效,则 -eq 返回 True;否则,-eq 返回 False-ne 执行相反操作;当双方等效时,它将返回 False;否则,-ne 返回 True

示例:

2 -eq 2                 # Output: True
2 -eq 3                 # Output: False
"abc" -eq "abc"         # Output: True
"abc" -eq "abc", "def"  # Output: False
"abc" -ne "def"         # Output: True
"abc" -ne "abc"         # Output: False
"abc" -ne "abc", "def"  # Output: True

当左侧是集合时,-eq 返回与右侧匹配的成员,同时 -ne 筛选掉它们。

示例:

1,2,3 -eq 2             # Output: 2
"abc", "def" -eq "abc"  # Output: abc
"abc", "def" -ne "abc"  # Output: def

这些运算符处理集合的所有元素。 示例:

"zzz", "def", "zzz" -eq "zzz"
zzz
zzz

相等运算符可以比较不同类型的对象。 请务必了解,比较右侧的值可以转换为左侧值的类型进行比较。

例如,字符串 '1.0' 转换为要与值 1 进行比较的整数。 此示例返回 True

PS> 1 -eq '1.0'
True

在此示例中,值 1 转换为要与字符串 '1.0' 进行比较的字符串。 此示例返回 False

PS> '1.0' -eq 1
False

相等运算符接受任意两个对象,而不仅仅是标量或集合。 但不能保证比较结果对最终用户有意义。 以下示例演示了此问题。

class MyFileInfoSet {
    [String]$File
    [Int64]$Size
}
$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$a -eq $b
False

在此示例中,我们创建了两个具有相同属性的对象。 然而,相等测试结果为 False,因为它们是不同的对象。 若要创建可比较类,需要在类中实现 System.IEquatable<T>。 以下示例演示 MyFileInfoSet 类的部分实现,该类实现 System.IEquatable<T>,并具有两个属性:文件大小。 如果两个 MyFileInfoSet 对象的文件和大小属性相同,Equals() 方法将返回 True

class MyFileInfoSet : System.IEquatable[Object] {
    [String]$File
    [Int64]$Size

    [bool] Equals([Object] $obj) {
        return ($this.File -eq $obj.File) -and ($this.Size -eq $obj.Size)
    }
}
$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$a -eq $b
True

比较任意对象的一个突出示例是找出它们是否为空。 但是,如果需要确定变量是否为 $null,则必须将 $null 放在相等运算符的左侧。 把它放在右侧不会做你期望的事情。

例如,让 $a 成为一个包含 null 元素的数组:

$a = 1, 2, $null, 4, $null, 6

以下测试 $a 不为空。

$null -ne $a
True

但是,以下从 $a 中排除所有空元素:

$a -ne $null # Output: 1, 2, 4, 6
1
2
4
6

-gt、-ge、-lt 和 -le

-gt-ge-lt-le 的行为非常相似。 当两侧是标量时,它们返回 TrueFalse,具体取决于双方的比较方式:

运算符 返回 True,当……
-gt 左侧更大
-ge 左侧大于或等于
-lt 左侧较小
-le 左侧较小或等于

在以下示例中,所有语句返回 True

8 -gt 6  # Output: True
8 -ge 8  # Output: True
6 -lt 8  # Output: True
8 -le 8  # Output: True

注意

在大多数编程语言中,大于运算符为 >。 在 PowerShell 中,此字符用于重定向。 有关详细信息,请参阅 about_Redirection

当左侧是集合时,这些运算符会将集合的每个成员与右侧进行比较。 根据逻辑,它们保留或放弃成员。

示例:

$a=5, 6, 7, 8, 9

Write-Output "Test collection:"
$a

Write-Output "`nMembers greater than 7"
$a -gt 7

Write-Output "`nMembers greater than or equal to 7"
$a -ge 7

Write-Output "`nMembers smaller than 7"
$a -lt 7

Write-Output "`nMembers smaller than or equal to 7"
$a -le 7
Test collection:
5
6
7
8
9

Members greater than 7
8
9

Members greater than or equal to 7
7
8
9

Members smaller than 7
5
6

Members smaller than or equal to 7
5
6
7

这些运算符适用于实现 system.IComparable 的任何类。

示例:

# Date comparison
[DateTime]'2001-11-12' -lt [DateTime]'2020-08-01' # True

# Sorting order comparison
'a' -lt 'z'           # True; 'a' comes before 'z'
'macOS' -ilt 'MacOS'  # False
'MacOS' -ilt 'macOS'  # False
'macOS' -clt 'MacOS'  # True; 'm' comes before 'M'

下面的示例演示了美国 QWERTY 键盘上没有符号,该键盘在“a”后排序。 它将包含所有此类符号的集馈送给 -gt 运算符,以将它们与“a”进行比较。 输出为空数组。

$a=' ','`','~','!','@','#','$','%','^','&','*','(',')','_','+','-','=',
   '{','}','[',']',':',';','"','''','\','|','/','?','.','>',',','<'
$a -gt 'a'
# Output: Nothing

如果运算符的两端无法合理比较,则这些运算符引发非终止错误。

匹配运算符

匹配运算符(-like-notlike-match-notmatch)查找匹配或不匹配指定模式的元素。 -like-notlike 模式是通配符表达式(包含 *?[ ]),而 -match-notmatch 接受正则表达式。

语法为:

<string[]> -like    <wildcard-expression>
<string[]> -notlike <wildcard-expression>
<string[]> -match    <regular-expression>
<string[]> -notmatch <regular-expression>

当这些运算符的输入是标量值时,它们返回布尔值。

当输入是值的集合时,集合中的每个项将转换为字符串以供比较。 -match-notmatch 运算符分别返回任何匹配成员和非匹配成员。 但是,-like-notlike 运算符将成员作为字符串返回。 -like-notlike 为集合成员返回的字符串是用于比较的运算符的字符串,并通过将成员转换为字符串来获取。

-like 和 -notlike

-like-notlike 的行为类似于 -eq-ne,但右侧可能是包含通配符的字符串。

示例:

"PowerShell" -like    "*shell"           # Output: True
"PowerShell" -notlike "*shell"           # Output: False
"PowerShell" -like    "Power?hell"       # Output: True
"PowerShell" -notlike "Power?hell"       # Output: False
"PowerShell" -like    "Power[p-w]hell"   # Output: True
"PowerShell" -notlike "Power[p-w]hell"   # Output: False

"PowerShell", "Server" -like "*shell"    # Output: PowerShell
"PowerShell", "Server" -notlike "*shell" # Output: Server

-match 和 -notmatch

-match-notmatch 使用正则表达式搜索左侧值的模式。 正则表达式可以匹配复杂的模式,例如电子邮件地址、UNC 路径或格式的电话号码。 右侧字符串必须遵循正则表达式规则。

标量示例:

# Partial match test, showing how differently -match and -like behave
"PowerShell" -match 'shell'        # Output: True
"PowerShell" -like  'shell'        # Output: False

# Regex syntax test
"PowerShell" -match    '^Power\w+' # Output: True
'bag'        -notmatch 'b[iou]g'   # Output: True

如果输入是集合,则运算符返回该集合的匹配成员。

集合示例:

"PowerShell", "Super PowerShell", "Power's hell" -match '^Power\w+'
# Output: PowerShell

"Rhell", "Chell", "Mel", "Smell", "Shell" -match "hell"
# Output: Rhell, Chell, Shell

"Bag", "Beg", "Big", "Bog", "Bug"  -match 'b[iou]g'
#Output: Big, Bog, Bug

"Bag", "Beg", "Big", "Bog", "Bug"  -notmatch 'b[iou]g'
#Output: Bag, Beg

-match-notmatch 支持正则表达式捕获组。 每次在标量输入上运行,-match 结果为 True,或者 -notmatch 结果为 False,它们都会覆盖 $Matches 自动变量。 $Matches 是一个哈希表,它始终具有名为“0”的键,用于存储整个匹配项。 如果正则表达式包含捕获组,则 $Matches 包含每个组的其他键。

请务必注意,$Matches 哈希表仅包含任何匹配模式的第一个匹配项。

示例:

$string = 'The last logged on user was CONTOSO\jsmith'
$string -match 'was (?<domain>.+)\\(?<user>.+)'

$Matches

Write-Output "`nDomain name:"
$Matches.domain

Write-Output "`nUser name:"
$Matches.user
True

Name                           Value
----                           -----
domain                         CONTOSO
user                           jsmith
0                              was CONTOSO\jsmith

Domain name:
CONTOSO

User name:
jsmith

-match 结果为 False,或者 -notmatch 结果为 True 或输入为集合时,不会覆盖 $Matches 自动变量。 因此,如果尚未设置变量,它将包含以前设置的值,或 $null。 在调用其中一个运算符后引用 $Matches 时,请考虑使用条件语句验证当前运算符调用是否设置了变量。

示例:

if ("<version>1.0.0</version>" -match '<version>(.*?)</version>') {
    $Matches
}

有关详细信息,请参阅 about_Regular_Expressionsabout_Automatic_Variables

替换运算符

替换为正则表达式

-match 一样,-replace 运算符使用正则表达式查找指定的模式。 但与 -match 不同,它将匹配项替换为另一个指定值。

语法:

<input> -replace <regular-expression>, <substitute>

运算符使用正则表达式将值的所有或部分替换为指定的值。 可以将运算符用于许多管理任务,例如重命名文件。 例如,以下命令将所有 .txt 文件的文件扩展名更改为 .log

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -replace '\.txt$','.log' }

默认情况下,-replace 运算符不区分大小写。 若要使其区分大小写,请使用 -creplace。 若要明确不区分大小写,请使用 -ireplace

示例:

"book" -ireplace "B", "C" # Case insensitive
"book" -creplace "B", "C" # Case-sensitive; hence, nothing to replace
Cook
book

从 PowerShell 7.2 开始,当 -replace 运算符语句中的左侧操作数不是字符串时,该操作数将转换为字符串。 PowerShell 执行不区分区域性的字符串转换。

例如,如果区域性设置为法语 (fr),则值 1.2 的区分区域性的字符串转换为 1,2

在 PowerShell 7.2 之前:

PS> [cultureinfo]::CurrentCulture = 'fr'
PS> 1.2 -replace ','
12

在 PowerShell 7.2 及更高版本中:

PS> [cultureinfo]::CurrentCulture = 'fr'
PS> 1.2 -replace ','
1.2

正则表达式替换

还可以使用正则表达式通过捕获组和替换来动态替换文本。 可以使用组标识符前的美元符号($)字符在 <substitute> 字符串中引用捕获组。

在以下示例中,-replace 运算符接受 DomainName\Username 形式的用户名,并转换为 Username@DomainName 格式:

$SearchExp = '^(?<DomainName>[\w-.]+)\\(?<Username>[\w-.]+)$'
$ReplaceExp = '${Username}@${DomainName}'

'Contoso.local\John.Doe' -replace $SearchExp, $ReplaceExp
John.Doe@Contoso.local

警告

$ 字符在 PowerShell 和正则表达式中都有语法角色:

  • 在 PowerShell 中,在双引号之间,它指定变量并充当子表达式运算符。
  • 在正则表达式搜索字符串中,它表示行尾。
  • 在正则表达式替换字符串中,它表示捕获的组。 请务必将正则表达式放在单引号之间,或在其前面插入反引号(`)字符。

例如:

$1 = 'Goodbye'

'Hello World' -replace '(\w+) \w+', "$1 Universe"
# Output: Goodbye Universe

'Hello World' -replace '(\w+) \w+', '$1 Universe'
# Output: Hello Universe

正则表达式中的 $$ 表示文本 $。 替换字符串中的此 $$,以在生成的替换中包含文本 $。 例如:

'5.72' -replace '(.+)', '$ $1' # Output: $ 5.72
'5.72' -replace '(.+)', '$$$1' # Output: $5.72
'5.72' -replace '(.+)', '$$1'  # Output: $1

若要了解详细信息,请参阅 about_Regular_Expressions正则表达式中的替换

在集合中替换

<input>-replace 运算符是集合时,PowerShell 会将替换应用于集合中的每个值。 例如:

"B1","B2","B3","B4","B5" -replace "B", 'a'
a1
a2
a3
a4
a5

使用脚本块替换

在 PowerShell 6 及更高版本中, -replace 运算符还接受执行替换的脚本块。 脚本块针对每个匹配运行一次。

语法:

<String> -replace <regular-expression>, {<Script-block>}

在脚本块中,使用 $_ 自动变量访问要替换的输入文本和其他有用信息。 此变量的类类型为 System.Text.RegularExpressions.Match

以下示例将每个三位数字的序列替换为字符等效项。 脚本块针对需要替换的每个三位数字集运行。

"072101108108111" -replace "\d{3}", {return [char][int]$_.Value}
Hello

包含运算符

包含运算符(-contains-notcontains-in-notin)类似于相等运算符,只是它们始终返回布尔值,即使输入是集合也是如此。 这些运算符在检测到第一个匹配项后立即停止比较,而相等运算符会评估所有输入成员。 在非常大的集合中,这些运算符的返回速度比相等运算符更快。

-contains 和 -notcontains

语法:

<Collection> -contains <scalar-object>
<Collection> -notcontains <scalar-object>

这些运算符指示集是否包含特定元素。 当右侧(标量对象)与集中的元素之一匹配时,-contains 返回 True。 而 -notcontains 返回 False。

示例:

"abc", "def" -contains "def"                  # Output: True
"abc", "def" -notcontains "def"               # Output: False
"Windows", "PowerShell" -contains "Shell"     # Output: False
"Windows", "PowerShell" -notcontains "Shell"  # Output: True
"abc", "def", "ghi" -contains "abc", "def"    # Output: False
"abc", "def", "ghi" -notcontains "abc", "def" # Output: True

更复杂的示例:

$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",
                 "ContosoDHCP","ContosoWSUS"
$thisComputer  = "ContosoDC2"

$DomainServers -contains $thisComputer
# Output: True

当右侧操作数是集合时,这些运算符将值转换为其字符串表示形式,然后再将其与左侧集合进行比较。

$a = "abc", "def"
"abc", "def", "ghi" -contains $a # Output: False

# The following statements are equivalent
$a, "ghi" -contains $a           # Output: True
"$a", "ghi" -contains $a         # Output: True
"abc def", "ghi" -contains $a    # Output: True

-in 和 -notin

语法:

<scalar-object> -in <Collection>
<scalar-object> -notin <Collection>

PowerShell 3 中引入了 -in-notin 运算符作为 -contains-notcontains 运算符的语法反转。 当左侧 <scalar-object> 与集合中的一个元素匹配时,-in 返回 True。 而 -notin 返回 False

以下示例执行与 -contains-notcontains 示例相同的操作,但它们是用 -in-notin 编写的。

"def" -in "abc", "def"                  # Output: True
"def" -notin "abc", "def"               # Output: False
"Shell" -in "Windows", "PowerShell"     # Output: False
"Shell" -notin "Windows", "PowerShell"  # Output: True
"abc", "def" -in "abc", "def", "ghi"    # Output: False
"abc", "def" -notin "abc", "def", "ghi" # Output: True

更复杂的示例:

$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",
                 "ContosoDHCP","ContosoWSUS"
$thisComputer  = "ContosoDC2"

$thisComputer -in $DomainServers
# Output: True

当左侧操作数是集合时,这些运算符将值转换为其字符串表示形式,然后再将其与右侧集合进行比较。

$a = "abc", "def"
$a -in "abc", "def", "ghi" # Output: False

# The following statements are equivalent
$a -in $a, "ghi"           # Output: True
$a -in "$a", "ghi"         # Output: True
$a -in "abc def", "ghi"    # Output: True

类型比较

类型比较运算符(-is-isnot)用于确定对象是否是特定类型。

语法:

<object> -is <type-reference>
<object> -isnot <type-reference>

示例:

$a = 1
$b = "1"
$a -is [int]           # Output: True
$a -is $b.GetType()    # Output: False
$b -isnot [int]        # Output: True
$a -isnot $b.GetType() # Output: True

另请参阅