Home > Back-end >  PowerShell: Ask Question to select file pth
PowerShell: Ask Question to select file pth

Time:03-11

I am trying to modify an existing PowerShell script. This script reached out to remote machines to check for the uptime and pending reboots. The script pulls the list of remote machines from a text file, and it is working great!

My ask; I'm trying to have the script ask a question in the beginning of the process to determine which list of machines to use. Example would be.. "Is this for Production?" Y/N

IF it is indicated via Y it would pull from $comps = Get-Content '\\networkpathhere\PostPatchingValidation\ServerListProd.txt'

IF it is indicated via N it would pull from $comps = Get-Content '\\networkpathhere\PostPatchingValidation\ServerListDev.txt'

CodePudding user response:

You can use Read-Host for this, another nice alternative could be the use of PSHostUserInterface.PromptForChoice method, this method will allow you to prompt user input with additional help messages and will also validate user input, meaning, the user must provide the right input (Y or N):

$title   = 'The title of my script'
$message = 'Is this for Production?'
$choice  = @(
    [System.Management.Automation.Host.ChoiceDescription]::new(
        '&Yes', 'This will execute on Prod!' # => This is help message
    )
    [System.Management.Automation.Host.ChoiceDescription]::new(
        '&No', 'This will execute on Lower Env!' # => This is help message
    )
)
$defaultCoice = 0 # => Yes

$userinput = $host.UI.PromptForChoice($title, $message, $choice, $defaultCoice)
$comps = if($userinput -eq 0) {
    Get-Content '\\networkpathhere\PostPatchingValidation\ServerListProd.txt'
}
else {
    Get-Content '\\networkpathhere\PostPatchingValidation\ServerListDev.txt'
}
  • Related