如何在Powershell中的指定点启动脚本

时间:2010-10-11 17:37:44

标签: powershell

我有一个powershell脚本,我希望能够为其定义不同的起点。一旦命中起点,脚本就会从该点开始接收并继续执行脚本中的其余代码。我不相信case语句会起作用,因为我认为不会让脚本从任何起点定义出来。

我希望在脚本启动时能看到类似的内容。

请选择您的起点:

  1. 开始
  2. 从第2步开始
  3. 从步骤3等开始......
  4. 当选择完成后,脚本跳转到该点,然后将运行脚本的其余部分。

    答案:代码最终会看起来像这样:

    #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!' 
    }
    

    感谢您的帮助

4 个答案:

答案 0 :(得分:5)

AFAIK,在PowerShell中没有这样的东西。如果您需要简单的东西,这可能适合您:

*)创建一个脚本,其中包含定义为函数的步骤。最后的每个函数都调用下一个步骤函数:

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

*)如果你想从第1步开始:dot-source the Steps.ps1并调用Step1:

. .\Steps.ps1
Step1

*)如果你想从第2步开始:dot-source the Steps.ps1并调用Step2:

. .\Steps.ps1
Step2

答案 1 :(得分:1)

对于这项特殊任务,这个额外答案可能太多了。 但了解该工具可能会有所帮助。 它可以用于类似和更复杂的任务。

该工具为Invoke-Build.ps1。 它是一个独立的脚本,只需将它放在路径中的任何位置,就是这样。 然后使用这样的代码:

Steps.ps1

# Invoke-Build task is a sequence of scripts and other tasks.
# This task does its job and then calls the task Step2.
task Step1 {
    'Step 1'
},
Step2

# This task does its job and then calls the task Step3.
task Step2 {
    'Step 2'
},
Step3

# The last task, just its name and code.
task Step3 {
    'Step 3'
}

Test.ps1

Invoke-Build step1 Steps.ps1 # do steps 1, 2, 3
Invoke-Build step2 Steps.ps1 # do steps 2, 3
Invoke-Build step3 Steps.ps1 # do just step 3

此回答和之前回答的区别在于任务方法 实际的步骤代码块不必显式依赖,即调用 其他一些步骤。任务基础设施将行动粘合在一起。

答案 2 :(得分:0)

PowerShell不包含GOTO类型命令,因此您必须在某种过程/代码块中封装每个逻辑步骤(Beginning,step2,step3,...)并根据需要进行调用。虽然如果你需要很多选择,switch语句将无法很好地扩展,但对于三个来说它会相当简单 - 这是一个想法,尽管我确信这个想法可以更好地实现:

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"

输出:

Starting
One
Two

答案 3 :(得分:0)

更直接的方法是使用一系列if语句,以便可以独立使用任何辅助函数,而无需交叉引用其他步骤。

[int]$stepChoice = read-host 'Where would you like to start.'

if( $stepChoice -le 1 ) {
  'Step 1'
}

if( $stepChoice -le 2 ) {
  'Step 2'
}

if( $stepChoice -le 3 ) {
  'Step 3'
}

'Done!'

另请注意,switch语句将继续评估条件,直到遇到break语句,因此此表单也可以使用:

switch( $stepChoice ) {
  { $_ -le 1 } { 'Step 1' }
  { $_ -le 2 } { 'Step 2' }
  { $_ -le 3 } { 'Step 3' }
}

'Done!'
相关问题