Is it possible to force PowerShell script to throw if a required parameter is omitted?

前端 未结 2 1811
醉话见心
醉话见心 2020-12-25 10:49

I would like the second function call in this script to throw an error:

function Deploy
{

param(

    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmp         


        
2条回答
  •  既然无缘
    2020-12-25 10:56

    Once the parameter is marked as mandatory PowerShell will prompt for value. That said, if you remove the mandatory attribute then you can set a default value with a throw statement:

    function Deploy
    {
        param(
            [Parameter()]
            [ValidateNotNullOrEmpty()]
            [string]$BuildName=$(throw "BuildName is mandatory, please provide a value.")
        )
    
        Write-Host "Build name is: $BuildName"
    }
    

提交回复
热议问题