相关疑难解决方法(0)

为什么我需要先在PowerShell脚本中编写函数?

我有一个脚本,我利用函数来包装部分代码,允许我在指定的点移动部分.我发现我必须在脚本中首先列出函数才能正确运行.

非工作的例子

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

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

}

# Steps.ps1 
function Step1 { 
    'Step 1' 
    Step2 
} 
function Step2 { 
    'Step 2' 
    Step3 
} 
function Step3 { 
    'Step 3' 
    'Done!' 
}
Run Code Online (Sandbox Code Playgroud)

错误

这给我以下错误:

术语"Step1"未被识别为cmdlet,函数,脚本文件或可操作程序的名称.检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试.

 At C:\Tools\Scripts\functiontest.ps1:7 char:12
  +     1{Step1 <<<< }
  + CategoryInfo          : ObjectNotFound: (Step1:String) [], CommandNotFoundException
  + FullyQualifiedErrorId : CommandNotFoundException*
Run Code Online (Sandbox Code Playgroud)

工作实例

如果我改变它的顺序它工作正常:

# Steps.ps1 
function Step1 { 
    'Step 1' 
    Step2 
} 
function Step2 { 
    'Step 2' 
    Step3 
} 
function …
Run Code Online (Sandbox Code Playgroud)

powershell coding-style

46
推荐指数
4
解决办法
3万
查看次数

标签 统计

coding-style ×1

powershell ×1