How to pass a switch variable?

假装没事ソ 提交于 2019-12-24 03:09:47

问题


& "$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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/30873846/how-to-pass-a-switch-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!