How do I create a PowerShell script that prompts for user input?
Asked by
hush now
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!
Answers
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!
Reply to this answer
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!
Reply to this answer
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!
Reply to this answer
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!
4C_spin: This looks great! I'll be trying this approach.
Reply to this answer
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.
crosscut: Nice! I appreciate the practical example.
Reply to this answer
Add your answer
Answers are reviewed before publication.
~rwy09_hold: Thanks for the tip! I'll look into how to implement that.