1

I am currently adding a Parameter to a script. The outcome I want is that if the script is run manually - that the user will get prompted like this for an input:

Press 1 for Option blah
Press 2 for Option bleh
Press 3 for Option blih
Press 4 for Option bloh

I've used an options array before:

$optionsarray = @()

$optionsarray += $Zero

foreach($_ in $variablearray){

$word = Convert-NumbertoWords $_

$tmp2 = (get-variable -name $_).value

$tmp = Write-Output $word[1].trim()

$tmp3 = New-Object System.Management.Automation.Host.ChoiceDescription "$tmp", "$tmp2"

New-Variable -Name $tmp -Value $tmp3

$optionsarray += $tmp3

}

#Combine the options array to an actual options object

$options = [System.Management.Automation.Host.ChoiceDescription[]]($optionsarray)

#prompt the user for the choice

$title = 'Select the Option'
$message = 'Hover over each option to check what the description is'
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
}

(this bit of code looped through multiple lines of an output, assigned a number to each one, so that the end-user could input a number to select the option)

I want to do something similar but with a Parameter. So they get prompted if they run it normally, or once they are familiar with it then can call it from the CLI e.g.

.\myscript.ps1 -option 1

But I'm not sure if this is possible to do in a mandatory parameter?

3
  • 1
    Can you explain what you mean by “run manually” and “run it normally”? That probably varies a lot for different people - I “normally” run all my scripts in a CI pipeline, but for someone else it might mean a “repl session”, and you can “manually” invoke a script with powershell .\myscript.ps1, interactive dot sourcing with . .\myscript.ps1 or by cut&pasting the script content, so it will help if you can be more specific about it…
    – mclayton
    Commented Jun 12, 2023 at 3:57
  • If the parameters are Mandatory, PowerShell will prompt the user for values.
    – lit
    Commented Jun 12, 2023 at 22:14
  • Have some assumptions like you have a customized prompt. By doing the Param method, you are limited to its message prompting for a value. However, it seems possible to leverage Param method in a non-mandatory way for user who can launch your script inline .\myscript.ps1 -option "notNULL" by utilizing same variable passed in the code. Commented Jun 13, 2023 at 5:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.