簡體   English   中英

如何將開關參數作為變量/通過 PowerShell 中的噴濺傳遞?

[英]How to pass a switch parameter as a variable / via splatting in PowerShell?

如果您有多個參數在調用命令或腳本時需要一個值,我知道您可以像這樣傳遞它:

$parameters = @{
    name = "John"
    last_name = "Doe"
}

但是,如果命令或腳本實際上只是期望-T指示類似標志的東西,但參數本身不需要值。 如何在變量中設置它?

$optionalT = ""
if ($itNeedsTheT) $optionalT = "-T"

command $optionalT

如果我這樣做,它會抱怨以下消息:

Unknown argument 'T' on command line.

splatting 時,使用非條件參數創建哈希表(值可以是可變的),但在創建哈希表后添加可選參數:

$parameters = @{
  Name = "John"
  LastName = "Doe"
  Age = $age
  Enabled = $true
}

if( $favoriteThing ){
  $parameters.FavoriteThing = $favoriteThing
}

command @parameters

如果在 splatting 中處理開關,您可以將其視為 boolean 參數,如上所示,只需根據您是否希望在命令上啟用開關,為其賦值$true$false 您可以看到將-Confirm標志設置為$false的非 splat 示例:

Install-Package some_package -Confirm:$false

tl;博士

# Pass the $itNeedsT Boolean - which indicates whether the -T switch should
# be passed - as the switch's *value*.
command -T:$itNeedsTheT  

如果$itNeedsTheT$false ,則上述內容與通常省略-T相同(請繼續閱讀以了解詳細信息)。

注意需要使用:將開關名稱與值分開。


正如boxdog在評論中指出的那樣,在與噴濺 ( @parameters )一起使用的哈希表中,您使用Boolean值來表示開關參數(類型為[switch]的類似標志的參數)。

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

# Define the hashtable for splatting...
$parameters = @{
  Path = '.'
  Recurse = $recurseIfTrue  # turn the -Recurse switch on or off
}

# ... and pass it to the target command.
# *Loosely speaking*, the following command is the same as either:
#   Get-ChildItem -Path '.' -Recurse  # if $recuseIfTrue was $true
# or:
#   Get-ChildItem -Path '.'           # if $recuseIfTrue was $false
Get-ChildItem @parameters

也就是說,粗略地說:

  • 使用$true傳遞開關
  • 使用$false通過開關。

這允許您保留單個哈希表定義,該定義無條件地包含 switch 參數,但其值可以通過編程方式確定。

警告

嚴格來說,哈希表條目Recurse = $true轉換為參數-Recurse:$true並且Recurse = $false不會轉換為省略參數,它轉換為傳遞-Recurse:$false

大多數情況下,省略開關-Foo並以$false值傳遞它 - 即-Foo:$false - 是等效的。

但是,命令可以檢測到差異,有時會采取不同的行動:

一個值得注意的例子是-Confirm通用(開關)參數:省略-Confirm表示尊重$ConfirmPreference首選項變量,而-Confirm:$false表示應覆蓋首選項變量(並且不應請求確認)。

如果您想在 PowerShell 腳本或 function 中自己做出這種區分,除了檢查$Foo ( -Foo ) 開關參數變量的值之外,您還可以調用$PSBoundParameters.ContainsKey('Foo')

如果您正在處理這樣的命令並且您想以編程方式強制省略開關參數,您將別無選擇,只能在單獨的步驟中有條件地為此開關添加一個條目:

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

# A 'Recurse' key now can NOT be included unconditionally,
# if you want to *omit* -Recurse in case $recurseIfTrue is $false
$parameters = @{
  Path = '.'
}

# Add a 'Recurse' entry only if the switch should be passed.
if ($recurseIfTrue) {
  $parameters.Recurse = $true
}

Get-ChildItem @parameters

最后,請注意,作為通過 splatting 以編程方式指定開關值的替代方法,您可以直接將動態值傳遞給開關

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

Get-ChildItem -Path . -Recurse:$recurseIfTrue

注意需要使用:將開關名稱與其值分開

這是必要的,因為使用慣用的空格將參數名稱與其值分開會導致 PowerShell 將 Boolean 解釋為下一個參數,因為開關參數通常不采用values

雖然很少使用,但這種基於:的語法適用於所有參數類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM