PowerShell:如何从命令行向函数传递参数并解决参数失效问题
解决PowerShell脚本参数传递失败的问题
原代码与问题现象
模块文件 test.psm1
function test{ Param( [string]$name, [string]$Id ) echo “Your name is $name” echo “Your Id is $Id” } Export-ModuleMember -Function test
脚本文件 test1.ps1
Import-Module ".\WindowsPowerShell\modules\test.psm1" -Verbose -Force test($name, $Id)
执行命令(CMD中)
.\test1.ps1 -name "joke" -Id 3
实际输出
Your name is Your Id is
期望输出
Your name is Joke
Your Id is 3
问题根源
- test1.ps1未声明参数:脚本本身没有定义
-name和-Id参数,外部传入的参数无法被捕获,$name和$Id会被当作未定义的空变量。 - 函数调用语法错误:PowerShell不支持
test($name, $Id)这种C#风格的调用方式,这会把$name,$Id当作一个数组传给函数的第一个参数,导致第二个参数$Id为空。 - 中文全角引号问题:模块里使用了中文引号
“”,PowerShell会将其视为字符串内容的一部分,而非语法符号,可能引发解析异常。
修复方案
修复后的 test.psm1
将中文引号替换为英文半角引号:
function test{ Param( [string]$name, [string]$Id ) echo "Your name is $name" echo "Your Id is $Id" } Export-ModuleMember -Function test
修复后的 test1.ps1
添加参数声明,并使用PowerShell标准的函数调用语法:
# 声明脚本要接收的参数 param( [string]$name, [string]$Id ) Import-Module ".\WindowsPowerShell\modules\test.psm1" -Verbose -Force # 使用命名参数调用函数,或直接用空格分隔位置参数 test -name $name -Id $Id # 也可简化为:test $name $Id
验证
重新执行命令.\test1.ps1 -name "joke" -Id 3,即可得到期望输出:
Your name is joke
Your Id is 3
内容的提问来源于stack exchange,提问作者Royston
相关产品推荐
相关产品推荐

