gpt4 book ai didi

powershell - 了解PowerShell运算符+和

转载 作者:行者123 更新时间:2023-12-02 23:12:41 25 4
gpt4 key购买 nike

PowerShell中+,运算符之间的确切区别是什么?例如,当仅尝试连接两个数组时,它们都产生相同的输出,但是我无法对,操作的结果进行排序,只能对+操作的结果进行排序:

$a = Get-ChildItem C:\
$b = Get-ChildItem C:\Windows
# Does not sort anything, actually is the same output as $a, $b
$a , $b | sort
# Sort actually works
$a + $b | sort

更让我感到困惑的是,两个运算符都返回相同的类型:
PS C:\> ($a,$b).getType().Name
Object[]
PS C:\> ($a+$b).getType().Name
Object[]

最佳答案

这两个运算符都会在您的场景中生成一个数组,但是逗号运算符不会对数组进行插值,因此您将在其中获得一个数组数组,而+运算符会将第二个数组的元素追加到第一个数组的元素之后。当您以JSON格式输出数组时,它将变得更加清晰:

PS C:\> $a = 1, 2
PS C:\> $b = 3, 4
PS C:\> ($a, $b) | ConvertTo-Json
[
{
"value": [
1,
2
],
"Count": 2
},
{
"value": [
3,
4
],
"Count": 2
}
]
PS C:\> ($a + $b) | ConvertTo-Json
[
1,
2,
3,
4
]

但是,您不能只是不加选择地使用 +运算符,因为它被重载并且根据第一个操作数的类型将产生不同的结果:

PS C:\> 1 + @(3, 4)         # integer addition (fails)
Method invocation failed because [System.Object[]] does not contain a method
named 'op_Addition'.
At line:1 char:7
+ 1 + @(3, 4)
+ ~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], ...
+ FullyQualifiedErrorId : MethodNotFound

PS C:\> "1" + @(3, 4) # string concatenation (succeeds)
13 4
PS C:\> @(1) + @(3, 4) # array append (succeeds)
1
3
4

关于powershell - 了解PowerShell运算符+和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com