在 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
}
uj5u.com熱心網友回復:
在 PowerShell 中,語法
$x = . { ... }是什么意思?
{ ... }是一個腳本塊,用于存盤運算式。.是點源運算子,可用于執行腳本塊。
放在一起時. { ... },腳本塊在被 PowerShell 解釋后立即執行。
它與 有何不同
$x = @( ... )?
@( ... )是陣列子運算式 operatorSystem.Array,您必須在 PowerShell中定義 a 的方法之一。
對于這種特殊情況,我看不到兩者之間的區別,因為您的腳本塊正在存盤 aSystem.Array并且點源運算子不會更改運算式的回傳型別。
但是,在包裝子運算式時,@( .. )您可以確保即使子運算式回傳,回傳也始終是一個陣列$null:
@( $null ).GetType() # is an array
(. { $null }).GetType() # is an error
如果您要使用該.Invoke()方法執行腳本塊,則不同之處在于回傳型別 from System.Arrayto Collection`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[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474165.html
標籤:电源外壳
