Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 将字符串变量转换为函数_Powershell - Fatal编程技术网

Powershell 将字符串变量转换为函数

Powershell 将字符串变量转换为函数,powershell,Powershell,我将设置脚本的步骤分为不同的函数。我希望有一天能够停止脚本。如果我重新启动脚本,它将继续我停止的最后一步。所以我把最后一步记录在一个临时文件中。如果我启动脚本,它将读取上次记录的tempfiles步骤,并在重新启动时跳到该步骤 Function Step1 { Set-Content -Path $TEMPFILE -value "Step1" #"Setting current step" into a temp file do first stuff #part in th functio

我将设置脚本的步骤分为不同的函数。我希望有一天能够停止脚本。如果我重新启动脚本,它将继续我停止的最后一步。所以我把最后一步记录在一个临时文件中。如果我启动脚本,它将读取上次记录的tempfiles步骤,并在重新启动时跳到该步骤

Function Step1 {
Set-Content -Path $TEMPFILE -value "Step1" #"Setting current step" into a temp file

do first stuff #part in th function. e.g. copy files, add access rights...

Step2 #calling the next function
}

Function Step2 {
Set-Content -Path $TEMPFILE -value "Step2"

do second stuff 

Step3...  
}

...Step 25
启动时,脚本检查Tempfile是否存在,并将最后一步添加到变量[String]

有没有办法让这个字符串变量进入“跳转到函数”序列? 比如:


PowerShell版本5.1.14393.3471…

假设
$GETSTEP
将脚本作为字符串包含:

if($GETSTEP){
  # Use ScriptBlock.Create() to create a scriptblock from a string
  $scriptBlock = [scriptblock]::Create($GETSTEP)
  &$scriptBlock
}

如果
$GETSTEP
包含要执行的函数的名称,则更简单-使用调用运算符(
&
)调用函数:

if($GETSTEP){
    & $GETSTEP
}

假设
$GETSTEP
将脚本作为字符串包含:

if($GETSTEP){
  # Use ScriptBlock.Create() to create a scriptblock from a string
  $scriptBlock = [scriptblock]::Create($GETSTEP)
  &$scriptBlock
}

如果
$GETSTEP
包含要执行的函数的名称,则更简单-使用调用运算符(
&
)调用函数:

if($GETSTEP){
    & $GETSTEP
}

这将创建函数getstep:

$function:getstep = [scriptblock]::Create($GETSTEP)

这将创建函数getstep:

$function:getstep = [scriptblock]::Create($GETSTEP)

您可以说
$function:myfunc=$scriptblock
谢谢您的回答!但是,'$GETSTEP'将是下一个函数的名称。@oberpiller简单得多,只需执行
&$GETSTEP
,然后您就可以说
$Function:myfunc=$scriptblock
,谢谢您的回答!但是,''$GETSTEP'将是下一个函数的名称。@oberpiller则简单得多,只需执行
和$GETSTEP