Powershell – 如何将命令行参数传递给模块中的函数?

huangapple go评论73阅读模式
英文:

Powershell - How Do I Pass Command Line Arguments to a Function in a Module?

问题

I've translated the code portion for you:

我编写了一个PowerShell模块用于在用户使用命令行参数请求帮助时显示帮助例如 **-show help-topic**我使用以下语句将其导入到主脚本中

```powershell
Import-Module Help-Module -ArgumentList $args

脚本调用模块函数如下:

Show-Help $args

这是被调用的函数:

function Show-Help {
    <#
    .SYNOPSIS
    查找指示用户请求帮助的命令行参数,如果存在,则显示请求的帮助。
    .OUTPUTS
    如果找到一个或多个帮助请求并回答,则为$true,否则为$false。
    如果帮助请求格式不正确,则引发错误。
    #>
    Write-Debug "Inside Show-Help"
    if ([string]::IsNullOrWhiteSpace($args)) {                     # 如果没有参数
        return $false                                               # 无需操作
    }
    if ($args.Length -gt 0 -and $args[0] -eq "-help") {            # 如果只是一般性的帮助请求
        Show-ScriptOverview                                         # 显示脚本概述
        return $true                                                # 完成
    }                                                              # 否则
    foreach ($argument in $args) {                                 # 检查每个参数
        Write-Host "参数类型是 $($argument.getType())"
        $argarray = $argument.split(' ')                  
        if ($argarray.length -eq 2 -and $argarray[0] -eq "-show") { # 如果是“show”请求
            switch ($topic = $($argarray[1])) {                      # 用户请求的是什么?
                default {throw "抱歉我们不知道 '$topic' 是什么意思"} # 除非我们不认识它
            }
            return $true
        }
    }
}

它输出 参数类型是 System.Object[]

然后在调用 $argument.split(' ') 时失败,显示以下消息:

方法调用失败,因为 [System.Object[]] 不包含名为 'split' 的方法

如何以可以获取字符串值的数据类型将命令行参数传递给模块函数?


<details>
<summary>英文:</summary>

I&#39;ve written a PowerShell module to show help when the user requests it with a command line parameter like **-show help-topic**. I import it into the main script with this statement:

Import-Module Help-Module -ArgumentList $args

Scripts call a module function like this:

Show-Help $args


This is the called function:

    function Show-Help {
    &lt;#
    .SYNOPSIS
    Looks for command line arguments indicating user requested help, and if they are present, displays the
    requested help.
    .OUTPUTS
    $true if one or more help requests were found and answered, else $false.
    Throws an error if a help request was malformed.
    #&gt;
       Write-Debug &quot;Inside Show-Help&quot;
       if ([string]::IsNullOrWhiteSpace($args)) {                     # If no arguments
          return $false                                               # Nothing to do
       }
       if ($args.Length -gt 0 -and $args[0] -eq &quot;-help&quot;) {            # If just a generic help request
          Show-ScriptOverview                                         # Show script overview
          return $true                                                # And we’re done
       }                                                              # Otherwise
       foreach ($argument in $args) {                                 # Examine each argument
          Write-Host &quot;Argument type is $($argument.getType())&quot;
          $argarray = $argument.split(&#39; &#39;)                  
          if ($argarray.length -eq 2 -and $argarray[0] -eq &quot;-show&quot;) { # If it’s a “show” request
             switch ($topic = $($argarray[1])) {                      # What is user requesting?
                default {throw &quot;Sorry, we don’t what &#39;$topic&#39; means&quot;} # Unless we don’t recognize it
             }
             return $true
          }
       }
    }

It outputs **Argument type is System.Object[]**

Then it fails on the call to `$argument.split(&#39; &#39;)` with this message:

**Method invocation failed because [System.Object[]] does not contain a method named &#39;split&#39;**

How can I pass command line arguments to a module function in a data type that I can get string values from?









</details>


# 答案1
**得分**: 2

Replace `Show-Help $args` with:

```sh
Show-Help @args

这样,使用 splatting 来传递你的脚本接收到的参数到 Show-Help 函数。

请注意,为了传递参数,无论你的函数是否在一个模块中定义都无关紧要。

关于你尝试的部分:

Show-Help $args

会将 自动的 $args 变量 作为一个 单一 参数传递给 Show-Help,这就解释了为什么在 Show-Help 内重新定义的 $args 变量在其第一个 - 也是唯一的 - 元素 $args[0] 中看到了一个 数组

英文:

<!-- language-all: sh -->

Replace Show-Help $args with:

Show-Help @args

That is, use splatting in order to pass the arguments that your script received through to the Show-Help function.

Note that for the purpose of relaying arguments it is irrelevant whether your function is defined in a module or not.


As for what you tried:

> Show-Help $args

passes the automatic $args variable as a single argument that is an array to Show-Help, which explains why the - redefined inside Show-Help - $args variable saw an array in its first - and only - element, $args[0]

huangapple
  • 本文由 发表于 2023年5月21日 03:11:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定