代码之家  ›  专栏  ›  技术社区  ›  Royston

Powershell:如何将参数从命令行传递给函数[复制]

  •  1
  • Royston  · 技术社区  · 5 月前

    测试.psm1

    function test{
    Param(
        
        [string]$name,
        [string]$Id
        )
      
    echo “Your name is $name”
        
    echo “Your Id is $Id”
    }
    Export-ModuleMember -Function test
    

    测试1.ps1

    Import-Module ".\WindowsPowerShell\modules\test.psm1" -Verbose -Force
    test($name, $Id)
    

    命令通过CMD行传递 :

    .\test1.ps1-名称“笑话”-Id 3

    O/P:

    你的名字是你的身份证是

    我希望输出为:

    你的名字叫小丑

    你的身份证号码是3

    2 回复  |  直到 5 月前
        1
  •  3
  •   mclayton    5 月前

    你有两个问题:

    • 你的 test.ps1 不声明任何参数,因此 $name $id 变量中没有值 测试ps1

    • 如果要向函数传递多个参数,请使用以下格式 test $name $id test -name $name -id $id , test($name, $Id) -您的版本相当于 test -name @($name, $id) -id $null 也就是说,括号定义了 阵列 值作为单个参数,而不是包含参数列表。请将此问题与其他几个具有相同问题的类似问题一起查看: PowerShell function parameters syntax

    文件的固定版本:

    测试.psm1

    function test
    {
        param(
            [string] $name,
            [string] $Id
        )
    
        echo "Your name is $name"
        echo "Your Id is $Id"
    }
    
    Export-ModuleMember -Function test
    

    测试ps1

    param(
        $name,
        $id
    )
    
    Import-Module ".\test.psm1" -Verbose -Force
    
    test -name $name -id $Id
    

    然后,您可以在命令行上调用它,如下所示:

    powershell .\test.ps1 -name "joke" -id 3
    

    获取输出

    Your name is joke
    Your Id is 3
    
        2
  •  0
  •   Razvan Tivadar    5 月前

    为了正确传递参数,您不必在命令中指定参数。所以它将是 .\test1.ps1 joke 3

    编辑:您也可以在此处查看此链接,它解释了如何将参数传递给Shell脚本 https://tecadmin.net/pass-command-line-arguments-in-shell-script/