如何传递开关变量?

时间:2015-06-16 17:03:53

标签: powershell parameter-passing

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

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

2 个答案:

答案 0 :(得分:4)

您可以使用splatting

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

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

如果$xtraOptions只是一个空哈希表,@xtraOptions对传递的参数没有任何影响。

您还可以使用条件值将所有参数推送到splatting表中:

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

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

答案 1 :(得分:2)

您可以将布尔值传递给切换参数,从而设置它们($true)或取消设置($false):

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