这个PowerShell语法是什么意思?



在powershell中$x =。{…}的意思吗?它与$x = @(…)有什么不同?据我所知,它们都创建了提供值的数组,但它们的输出略有不同。

当作者在异步示例中定义处理程序时,我在这个脚本https://powershell.one/tricks/filesystem/filesystemwatcher中遇到了它。这样做有什么意义吗?filewatcher的其他异步示例使用类似的代码。

$x = @(1,2,3)
$y = . {1,2,3}
@($x,$y) | foreach-object {
$_
$_.GetType()
}
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
1,2,3
True     True     Object[]                                 System.Array
1
2
3

非平凡示例

$handlers = . {
Register-ObjectEvent -InputObject $watcher -EventName Changed  -Action $Action 
Register-ObjectEvent -InputObject $watcher -EventName Created  -Action $Action
Register-ObjectEvent -InputObject $watcher -EventName Deleted  -Action $Action
Register-ObjectEvent -InputObject $watcher -EventName Renamed  -Action $Action
}

在PowerShell中语法$x = . { ... }是什么意思?

  • { ... }是一个脚本块,用于存储表达式。
  • .是点源操作符,可用于执行脚本块

当放在一起时,. { ... },脚本块被PowerShell解释后立即执行。

$x = @( ... )有何不同?

  • @( ... )是数组子表达式操作符,是在PowerShell中定义System.Array的一种方式。

对于这个特殊的情况,我没有看到两者之间的区别,因为您的脚本块正在存储System.Array并且点源操作符不会改变表达式的返回类型。

然而,当在@( .. )中包装子表达式时,即使子表达式返回$null:

,也可以确保返回始终是数组
@( $null ).GetType()    # is an array
(. { $null }).GetType() # is an error

如果您要使用.Invoke()方法来执行脚本块,那么从System.ArrayCollection`1的返回类型将有所不同:

({1, 2, 3}.Invoke()).GetType()
IsPublic IsSerial Name              BaseType
-------- -------- ----              --------
True     True     Collection`1      System.Object

至于链接的代码,作者在脚本块内包装对Register-ObjectEvent的多个调用并执行它,也没有区别,因为对cmdlet有多个调用,两个表达式的返回类型都是数组。但是,如果我们在脚本块示例中只调用一次cmdlet,那么我们将得到Register-ObjectEvent的输出类型:

$watcher1 = [System.IO.FileSystemWatcher]::new($pwd.Path)
$watcher2 = [System.IO.FileSystemWatcher]::new($pwd.Path)
$handler1 = . {
Register-ObjectEvent $watcher1 -EventName Changed -Action { Write-Host 'hello '}
}
$handler2 = @(
Register-ObjectEvent $watcher2 -EventName Changed -Action { Write-Host 'hello '}
)
$handler1.GetType() # => PSEventJob
$handler2.GetType() # => object[]

最新更新