Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a script at a specified point in Powershell

Tags:

powershell

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

like image 489
Dan Snell Avatar asked Oct 11 '10 17:10

Dan Snell


People also ask

How do I run a ps1 script from the command line?

ps1. Then, to execute the PowerShell script from the command line, launch the Windows command line by typing "cmd" into the search box and clicking the result. Type the full path of the PowerShell script, such as "C:\Example\example_script. ps1" and press enter.

How do I set a breakpoint in PowerShell?

Right-click the line where you want to set a line breakpoint, and then click Toggle Breakpoint. Or, click the line where you want to set a line breakpoint, and press F9 or, on the Debug menu, click Toggle Breakpoint.


1 Answers

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
like image 105
Roman Kuzmin Avatar answered Sep 24 '22 18:09

Roman Kuzmin