0

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.

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your response. Sounds like a solid answer. I recently started scripting and could you explain your code more to a beginner? I do not completely understand what the code is doing.
I already figured it out with your code. Thank you very much. This wil work perfectly.
Could you explain to me why you would not recommend my way of doing so I can learn from my mistakes?
You distribute things that belong together (prompt and reading the input) across different sections of your code. That just obfuscates your code. Also, always ask yourself "what do I gain by delegating a function call". If the answer is "nothing" (like in this case): don't do it.