How to pass a switch variable?

784 Views Asked by At
& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" `
    -Verbose -ProjectFilePath $project -PO "$packOptions" -NPFPPTNG                

So if I provide the command line above in PowerShell the call works correctly.

If I try something like this:

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

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

this fails. How can I pass a switch in a variable?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use splatting:

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

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

If $xtraOptions is just an empty hashtable, @xtraOptions will simply have no effect on the parameters passed.


You could also push all the parameters into the splatting table with a conditional value:

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

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

You can pass boolean values to switch parameters causing them to be set ($true) or unset ($false):

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