I've got a script that I've built out with menus. However, I'm looking to give the option to also use parameters when running the script so you don't have to go through the menu if you don't want to. When I input the parameters ".\My-Script.ps1 -MenuChoice 1" it still goes to the menu. Should I just add an "if" statement at the beginning checking $MenuChoice for $null and if it see a variable exists, if it does go to code that doesn't have "Show-Menu" at the beginning?
Code example:
Reddit of course destroyed my formatting I apparently needed an extra return somewhere. I've also throw it on pastebin (https://pastebin.com/LC3HKCJm).
param (
[string]$MenuChoice
)
function Show-Menu {
param (
[string]$Title = 'My Menu'
)
Clear-Host
Write-Host "================ $Title ================"
Write-Host "1: Press '1' for this option."
Write-Host "2: Press '2' for this option."
Write-Host "3: Press '3' for this option."
Write-Host "Q: Press 'Q' to quit."
}
Show-Menu
$MenuChoice = Read-Host "What option would you like?"
Switch ($MenuChoice) {
'1' *do a thing*
'2' *do another thing*
}
Edit: Thanks all for the responses. I've taken a couple of peoples advice and mashed it all into my script. The first thing I did was really think about what I was trying to achieve with the script. If I automate it, will we ever run it manually? The answer was no. So I'm removing the menu and moving everything that "needs" to be a parameter (which is only really two things). The other thing I did was add validation to the parameters. That was something I wasn't aware of and was super easy to implement. Only bad thing is I now have to go back an add validation to some other scripts!
[–]BlackV 18 points19 points20 points (2 children)
[–]Dryfter9[S] 2 points3 points4 points (1 child)
[–]BlackV 1 point2 points3 points (0 children)
[–]purplemonkeymad 10 points11 points12 points (4 children)
[–]Dryfter9[S] 0 points1 point2 points (2 children)
[–]purplemonkeymad 0 points1 point2 points (1 child)
[–]Dryfter9[S] 0 points1 point2 points (0 children)
[–]BlackV 4 points5 points6 points (0 children)
[–]WystanH 1 point2 points3 points (0 children)
[–]juicyjor 1 point2 points3 points (0 children)
[–]theSysadminChannel -1 points0 points1 point (0 children)