简体   繁体   中英

PowerShell passing function as parameter

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 .

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM