我不確定這是否可行,但我想知道在 Powershell 中使用 cmdlet 時是否有一種優雅的“動態”方式來使用或不使用屬性。
例如,在下面的代碼中,如何-directory根據某些條件設定屬性是否存在?
gci $folder_root -recurse -directory | ForEach{
# do something
}
uj5u.com熱心網友回復:
您可以通過稱為splatting的技術有條件地向呼叫添加引數引數。
您需要做的就是構造一個類似字典的物件并添加您可能想要傳遞給那里的呼叫的任何引數:
# Create empty hashtable to hold conditional arguments
$optionalArguments = @{}
# Conditionally add an argument
if($somethingThatMightBeTrue){
# This is equivalent to having the `-Directory` switch present
$optionalArguments['Directory'] = $true
}
# And invoke the command
Get-ChildItem $folder_root -Recurse @optionalArguments
請注意,我們使用splat指定的任何變數@都$在呼叫站點使用而不是指定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395658.html
