Reputation:
I have two PS scripts (1 main script and 1 as a module).
Main script uses code like:
Write-Host "Press Y to continue"
Execute (ConstructSshSessions)
Where Execute
is a function that asks the question to continue and execute the script in the function ConstructSshSessions
. If the users does not type a Y
then the main scripts skips the function ConstructSshSessions
.
Module uses code like:
Function Execute($function)
{
$response = read-host
Write-Host "You typed: $response"
if ($response -eq "Y")
{
$function
}
Remove-Variable response
}
When I execute the code Excecute (ConstructSshSession)
it first runs the script that creates the SSH sessions and then asks the user to continue. So that is clearly not my intention but I do not see the error.
I would like that it asks the users if it may continue and then execute the script that is beeing send as a parameter to the function Execute
.
Upvotes: 0
Views: 595
Reputation: 200523
I wouldn't recommend separating prompting for a response from actually reading the response. I wouldn't recommend passing a function name to some Exec
-like invocation routine either.
Wrap the confirmation routine in a function that returns a boolean value and invoke the function as the condition of an if
statement.
function ConfirmStep($msg) {
$title = 'Confirm Step'
$yes = New-Object Management.Automation.Host.ChoiceDescription '&Yes'
$no = New-Object Management.Automation.Host.ChoiceDescription '&No'
$options = [Management.Automation.Host.ChoiceDescription[]]($no, $yes)
$default = 1 # $yes
[bool]$Host.UI.PromptForChoice($title, $msg, $options, $default)
}
if (ConfirmStep "Construct SSH sessions?") {
ConstructSshSessions
}
Upvotes: 1