tags:

views:

39

answers:

2

I have a powershell script I want to be able to define different starting points for. Once the starting point is hit the script would pick up from that point and continue through the remaining code in the script. I don't believe that a case statement will work since I don't think that will just let the script flow through from whatever starting point is defined.

I would expect to see something like this when the script was started.

Please choose your starting point:

  1. Beginning
  2. Start at step 2
  3. Start at step 3 etc.....

When the selection is made the script jumps to that point then will run through the remainder of the script.

Answer: The code is going to end up looking something like this:

#steps
$stepChoice = read-host 'Where would you like to start.'

switch($stepChoice)
{
    1{Step1}
    2{Step2}
    3{Step3}

}

function Step1 { 
    'Step 1' 
    Step2 
} 
function Step2 { 
    'Step 2' 
    Step3 
} 
function Step3 { 
    'Step 3' 
    'Done!' 
}

Thanks for your help

A: 

PowerShell doesn't contain a GOTO type command, so you must encapsulate each of the logic steps (Beginning, step2, step3, ...) in a procedure/code block of some kind and call as appropriate. While a switch statement won't scale well if you need a lot of choices, for three it would be fairly simple - here is an idea, though I am sure this idea can be implemented better:

function Begin () { "Starting" }
function Step-1 () { "One" }
function Step-2 () { "Two" }

function Take-Action() {
  param([string]$choice);
  switch ($choice) {
    "Start" { & Begin ; Take-Action "One" }
    "One" { & Step-1; Take-Action "Two" }
    "Two" { & Step-2 }
  }
}

& Take-Action "Start"

Output:

Starting
One
Two
Goyuix
+1  A: 

AFAIK, there is nothing like this in PowerShell. If you need something simple this might work for you:

*) Create a script with steps defined as functions. Each function in the end calls the next step-function:

# Steps.ps1
function Step1 {
    'Step 1'
    Step2
}
function Step2 {
    'Step 2'
    Step3
}
function Step3 {
    'Step 3'
    'Done!'
}

*) If you want to start with step 1: dot-source the Steps.ps1 and call Step1:

. .\Steps.ps1
Step1

*) If you want to start with step 2: dot-source the Steps.ps1 and call Step2:

. .\Steps.ps1
Step2
Roman Kuzmin