How do I create a PowerShell script that prompts for user input?

0
0
Asked By CreativeNinja42 On

I'm trying to write a PowerShell script that executes commands based on user input. I want users to choose a group tag, like "NewYork" or "Amsterdam", and select between online and offline modes. Depending on these inputs, I need the command to be formed like `Get-WindowsAutopilotInfo -Grouptag $grouptag`. Furthermore, if the user selects offline, I want the output to be saved as a CSV file. Is this feasible? Any guidance would be greatly appreciated!

5 Answers

Answered By PowerShellPro On

If you're looking for more control, you could build your own choice prompts using `Read-Host` and loops to ensure valid input, as shown below:

```powershell
$groupTagOptions = @{
1 = "newyork"
2 = "amsterdam"
}
# Rest of the script...
```
This allows you to verify the input and loop until you get a valid response.

NewbieScripter -

Nice! I appreciate the practical example.

Answered By ScriptingGuru22 On

Here's a quick example that might help you get started:
```powershell
$GroupTag = $host.ui.PromptForChoice("Tag","Which tag do you want to use",("&NewYork","&Amsterdam"),-1)
$Mode = $host.ui.PromptForChoice("Mode","Choose network mode",("Online","Offline"),0)
```
This code sets up a choice prompt for the group tag and mode. You might need to handle the output based on these choices separately!

CuriousCoder55 -

This looks great! I'll be trying this approach.

Answered By TechWizard99 On

You can definitely achieve that! A recommended approach is to use `$Host.UI.PromptForChoice`, which simplifies the process. For instance, you can present the user with options for group tags and modes in a straightforward manner. Just ensure to set the parameters based on the user's choice. Check out the documentation on this method for more details!

HelpfulUser1 -

Thanks for the tip! I'll look into how to implement that.

Answered By ScriptMaster87 On

For a simple alternative, consider using `Out-GridView` to present the options in a GUI. This makes it easy for users to select from the displayed options, like in this example:

```powershell
$processes = Get-Process
$selectedProcess = $processes | Out-GridView -Title "Select a Process" -PassThru
```
This can enhance user experience in your script!

Answered By CodeNinja99 On

For validations, check out the `ValidateSet` attribute which can prevent users from entering unexpected choices. It also helps with tab completion which is super handy!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.