微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何基于脚本参数即msbuild,gradle在Powershell中实现任务

如何解决如何基于脚本参数即msbuild,gradle在Powershell中实现任务

是否可以在PowerShell中实现任务样式的系统,以便您可以执行以下操作:

.\script.ps1 build # runs build() function
.\script.ps1 publish # runs publish() function

我希望使用PowerShell来构建/发布应用程序,而不是要求用户安装gradle / msbuild,并且希望避免为每个添加功能更新switch语句。

目前这很混乱:

#!/usr/bin/env powershell

param(
    $action = 'build'
)

function build() {
    echo 'build';
}

function publish() {
    echo 'publish';
}

switch($action) {
    'build' { build; }
    'publish' { publish; }
}

解决方法

您可以使用&(即call operator)来执行名称为 的命令(例如函数)(或者对于外部可执行文件来说,则是这样) , path )存储在变量中。

但是,正如marsze所指出的那样,按名称盲目调用函数意味着您最终可能会调用与脚本不相关的命令(任何形式)。最好是无意识的,最坏的情况是安全风险。

谢天谢地,PowerShell提供了丰富的反射功能,还公开了自己的解析API,因此您可以确定脚本本身中实际定义了哪些功能,并且仅允许调用这些功能。

请注意,下面的代码还定义了list任务,其中列出了脚本中定义的所有任务(功能)的名称。

#!/usr/bin/env powershell

param(
  [string] $task = 'build'
)

# -- Define a function for each task.
#    Note that functions must be defined *before* they are called in PowerShell.

function list {
  "Available tasks:"
  $functionNames
}

function build {
  'build'
}

function publish {
  'publish'
}

# -- Invoke the specified task by invoking the function of the same name.

# Get the list of the names of all functions defined in this script.
$functionNames = $MyInvocation.MyCommand.ScriptBlock.Ast.FindAll(
   { $args[0] -is [Management.Automation.Language.FunctionDefinitionAst] },$false
).Name

if ($task -in $functionNames) {

  # A known task - invoke it.
  & $task

}
else {

  # Report a script-terminating error,if the task name is uknown.
  throw "Unknown task: $task"
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。