当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 运算符 [完整指南]

作者:精品下载站 日期:2024-12-14 03:45:54 浏览:11 分类:玩电脑

PowerShell 运算符 [完整指南]


使用 PowerShell 时,您可以在脚本中使用各种运算符。它们可以在命令或表达式中使用,并用于执行比较、定义条件或分配和操作值。

如果您使用的是 PowerShell 7,那么您还可以使用新的三元运算符。这些允许您创建在线 if-else 语句,使您的代码更具可读性。

在本文中,我们将了解不同的运算符。我把它们分成了几组,这样你就可以很容易地参考它们。

赋值运算符

最常用的运算符是赋值运算符。这些运算符用于为变量赋值、操作或附加值。

OperatorExampleDescription=$a = 5Assigns the value on the right to the left.+=$a += 3Adds the right operand to the left and assigns it.-=$a -= 2Subtracts the right operand from the left and assigns it.*=$a *= 4Multiplies the left operand by the right and assigns it./=$a /= 2Divides the left operand by the right and assigns it.

例如,我们可以将值 10 赋给变量 $count 并加上 5,使总数达到 15:

$count = 10
$count += 5
Write-Output $count  # Outputs 15

比较运算符

PowerShell 中的比较运算符可分为 4 组。我们有运算符来比较值,例如,用 ($a -gt $b) 测试 $a 是否大于 $b,还有用于查找甚至替换的运算符模式,测试一个值是否出现在集合中并检查一个对象是否是特定类型。

PowerShell 中的基本比较运算符有:

OperatorExampleDescription-eq5 -eq $aReturns True if both operands are equal.-ne5 -ne $aReturns True if operands are not equal.-gt$a -gt 5Returns True if the left operand is greater.-lt$a -lt 5Returns True if the left operand is less.-ge5 -ge $aReturns True if the left operand is greater or equal.-le5 -le $aReturns True if the left operand is less or equal.

正如您在上表中看到的,使用相等运算符时变量位于右侧。原因是当您在数组和标量值(如数字)之间使用 -eq 运算符时,PowerShell 不会返回 True 错误。

相反,它会将标量值与数组中的每个元素进行比较。如果数组中存在标量值,则它将返回数组元素而不是 True。

$a = 0,1,2,3
$a -eq 0 # Returns 0
0 -eq $a # Returns False

我们还有比较运算符,可用于查找甚至替换字符串中的模式。 -match-replace 运算符使用正则表达式进行比较,而 -like 运算符使用通配符。

OperatorExampleDescription-match$string -match “foo”Returns True if the string matches the regex pattern.-notmatch$string -notmatch “foo”Returns True if the string does not match the regex pattern.-replace$string -replace “foo”, “bar”Replaces text that matches a regex pattern.-like$string -like “foo*”Returns True if the string matches the wildcard pattern.-notlike$string -notlike “foo*”Returns True if the string does not match the wildcard pattern.

包含比较运算符用于检查引用集中(例如数组)中是否存在值。 -contains-in 这两个运算符都可用于检查集合中是否存在某个项目。

两者唯一的区别在于价值和收藏的地点。您应该使用哪一个实际上取决于上下文。

OperatorExampleDescription-contains$array -contains 5Returns True if the array contains the specified value.-notcontains$array -notcontains 5Returns True if the array does not contain the value.-in5 -in $arrayReturns True if the left operand is in the array.-notin5 -notin $arrayReturns True if the left operand is not in the array.
$numbers = 2, 4, 6, 8, 10

if ($numbers -contains 4) {
    Write-Output "The array contains 4."
}

我们可以在 PowerShell 中使用的最后一个比较运算符是 -is 运算符。这个用得不多,但允许您检查对象是否属于指定类型。

-is

$object -is [类型]

-isnot

$object - 不是 [类型]

逻辑运算符

逻辑运算符用于将 PowerShell 中的条件语句连接到单个语句。

OperatorExampleDescription-and(5 -gt 3) -and (6 -gt 2)Returns True if both conditions are true.-or(5 -gt 7) -or (8 -gt 2)Returns True if any of the conditions are true.-not-not (5 -eq 5)Reverses the logic of its operand.!!(3 -eq 4)Short form of -not.

例如,我们可以使用 -and 运算符通过以下命令检查值是否小于 10 且大于 2:

$val = 5
if ($val -lt 10 -and $val -gt 2)  {
    Write-Output "Both conditions are met"
}

重定向运算符

PowerShell 中的重定向运算符与命令提示符中的重定向运算符有一些相似之处。但 PowerShell 也有自己的一些功能。

您可以使用重定向运算符将命令的输出发送到文本文件。不同的选项不仅允许您将正常(标准)输出发送或附加到文件。也可以仅重定向错误流或警告流。当您想为脚本创建错误日志时,这非常有用。

OperatorExampleDescription>Get-Process > processes.txtRedirects standard output to a file.>>Get-Process >> log.txtAppends standard output to a file.2>Get-Command xyz 2> errors.txtRedirects error output to a file.2>>Get-Command xyz 2>> errors.logAppends error output to a file.2>&1Get-Process 2>&1 alloutput.txtRedirects error stream to the succes stream*>Get-Process *> alloutput.txtRedirects all streams to a file

例如,要仅将命令的错误写入文件,我们可以使用重定向流运算符:

# Write only the error to the file:
Get-ProcessCpu -name "explorer2" 2> C:\temp\process-error-log.txt

拆分和连接运算符

拆分和连接运算符用于拆分或连接字符串。

-split

‘一、二、三’ - split ‘,’

-join

('一','二') - 连接','

类型运算符

我们在比较运算符部分也看到了类型运算符 -is。该运算符用于检查变量是否属于特定类型。但除了 -is 运算符之外,我们还可以使用 -as 运算符将变量转换为特定类型。

OperatorExampleDescription-is$var -is [int]Checks if a variable is of a specified type.-as$var -as [string]Tries to convert a variable to a specified type.[Type][int]$varCasts a variable to a specified type.

例如,当您需要将字符串转换为整数时,-as 运算符特别方便

$number = "123"
if ($number -is [string]) {
    $converted = $number -as [int]
    Write-Output "Converted: $converted"
}

一元运算符

一元运算符被大量使用,尤其是在循环中,以跟踪索引或进行计数。有趣的是,++ 运算符可能是最常用的,但大多数人不知道它被称为一元运算符。

OperatorExampleDescription–-$varNegates the value of the operand.++++$varIncrements the operand’s value by 1.—–$varDecrements the operand’s value by 1.

特殊操作员

这些运算符并不真正适合其他组,因为每个运算符都有自己的特殊用例

OperatorExampleDescription&& script.ps1Executes a script or command... script.ps1Executes a script in the current scope.()($a + $b) * $cEnsure that expressions are evaluated in a specific order$( )$(Get-Date)Subexpression operator; runs the command in a subexpression.`“This is a backtick `n”Escape character; used to include special characters in strings...$a = 1..10Create an array with a range of integer from 1 to 10.

分组运算符(俗称括号)用于确保表达式或 cmdlet 按特定顺序执行。在下面的示例中,我们希望首先获取项目路径,然后检查长度是否大于 100。

$path = "C:\MyScripts\script.ps1"
if ((Get-Item $path).Length -gt 100) {
 Write-Host "Long path"
}

三元运算符表

三元运算符在 PowerShell 7 中发布。它简化了 if-else 语句,使它们更易于阅读。我确实建议仅对适合单行的简短 if-else 语句使用三元运算符。

OperatorExampleDescription? :$result = ($x -gt 10) ? ‘High’ : ‘Low’Returns High if $x is greater than 10,
otherwise returns Low.

在下面的示例中,我们检查变量 $x 是否大于 10,如果是这种情况,我们将状态设置为高,否则设置为低:

# Define a variable
$x = 15

# Use the ternary operator to assign a value based on a condition
$status = ($x -gt 10) ? 'High' : 'Low'

# Output the result
Write-Output "The status is $status"

空合并运算符

PowerShell 7 中的 null 合并运算符 ?? 允许您快速检查给定变量是否为 null 并设置默认值。

如果运算符左侧的值等于 null,则返回右侧的值(也可以是变量)。您还可以组合多个空合并运算符来查找第一个非空值。

OperatorExampleDescription??$result = $value ?? DefaultValueReturns $value if it is not null; otherwise, returns DefaultValue.??=$value ??= DefaultValueAssigns DefaultValue to $value if $value is null.?.$result = $object?.PropertyAccesses Property of $object only if $object is not null.?[]$element = $array?[index]Accesses the element at index in $array only if $array is not null.

空合并运算符的好处之一是,例如,它允许您仅在对象不为空时访问该对象的属性:

# Define an object with a property
$person = [PSCustomObject]@{ Name = "Alice" }

# Access the 'Name' property only if $person is not null
$name = $person?.Name

总结

PowerShell中有很多我们可以使用的运算符。大多数都很常见,也用于其他编程语言。但如果您对脚本或编程比较陌生,请务必特别注意 PowerShell 7 的空合并和三元运算符。

希望您觉得此列表有用,请务必订阅时事通讯或在 Facebook 上关注我,这样您就不会错过最新文章。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯