如何传递开关变量?

How to pass a switch variable?

& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" `
    -Verbose -ProjectFilePath $project -PO "$packOptions" -NPFPPTNG                

因此,如果我在 PowerShell 中提供上述命令行,调用将正常进行。

如果我尝试这样的事情:

if ($NoPromptForPushPackageToNuGetGallery) {
    $xtraOptions += " -NPFPPTNG "
}

& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" `
    -Verbose -ProjectFilePath $project -PO "$packOptions" $xtraOptions     

这失败了。如何在变量中传递开关?

您可以使用 splatting:

$xtraOptions = @{}
if ($NoPromptForPushPackageToNuGetGallery) {
    $xtraOptions.Add("NPFPPTNG",$true)
}

& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" -Verbose -ProjectFilePath $project -PO "$packOptions" @xtraOptions

如果$xtraOptions只是一个空散列table,@xtraOptions将对传递的参数没有任何影响。


您还可以将所有参数推入具有条件值的 table:

$nuGetOptions = @{
    PushOptions     = "$pushOptions"
    ProjectFilePath = $project 
    PO              = "$packOptions"
    Verbose         = $Verbose
    NPFPPTNG        = if($NoPromptForPushPackageToNuGetGallery) { $true } else { $false }
}

& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" @nuGetOptions

您可以将布尔值传递给开关参数,使它们被设置 ($true) 或取消设置 ($false):

& "New-NuGetPackage.ps1" -PushOptions "$pushOptions" `
  -Verbose -ProjectFilePath $project -PO "$packOptions" `
  <b>-NPFPPTNG:$NoPromptForPushPackageToNuGetGallery</b>