How to prevent PowerShell from prompting on Mandatory parameter on CI
When we use the mandatory parameter with PowerShell, it prompts. I’m considering using the script on the Continuous integration, so that I don’t want it.
ParamSpike.ps1
param(
[Parameter(Mandatory=$true, HelpMessage="Number of the Stage. e.g. 0")]
[int]
$stage
)
Write-Host $stage
Execute it
> mv .\ParamPike.ps1 .\ParamSpike.ps1
PS C:\Users\tsushi\Code\PowerShell> .\ParamSpike.ps1
cmdlet ParamSpike.ps1 at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
stage:
Oh. This is what I want to avoid in CI environment. I want some option like -y
of the apt-get
.
Answer
Don’t need it. The king of powershell told me.
If this is invoked directly from an interactive session, yes, otherwise — no, this will just cause an exception.
I tested with Azure DevOps, it successfully fail without prompt!!!!
Why I wrote it?
I search on the internet and disillusioned the workaround for example, $sourceVersion=$(throw “The sourceValueis mandatory, please provide a value. e.g. -sourceVersion 3.0.15417”) It works, however, I was wondering if there is better approach. For someone who is the same as me.