我写了一个完整的 PowerShell 脚本,其中包含一个带参数的函数(例如:function name (param) { } ),在此之下是对该函数的调用,同时带上参数。
我想能够在 .ps1 文件中调用此函数,并传入参数。如何通过 .bat 或 .cmd 文件打包调用这个函数?我使用的是 Powershell v2.0。
我写了一个完整的 PowerShell 脚本,其中包含一个带参数的函数(例如:function name (param) { } ),在此之下是对该函数的调用,同时带上参数。
我想能够在 .ps1 文件中调用此函数,并传入参数。如何通过 .bat 或 .cmd 文件打包调用这个函数?我使用的是 Powershell v2.0。
您应该使用所谓的“点源”脚本和带有多个语句的命令:脚本的点源 + 带参数的函数调用。
测试脚本Test-Function.ps1:
function Test-Me($param1, $param2)
{
"1:$param1, 2:$param2"
}
调用的.bat文件:
powershell ". .\Test-Function.ps1; Test-Me -Param1 'Hello world' -Param2 12345"
powershell ". .\Test-Function.ps1; Test-Me -Param1 \"Hello world\" -Param2 12345"
注意:这不是必需的,但如果需要在命令文本中使用内部引号,请使用CMD转义规则并用双引号将整个命令文本括起来,我建议这样做。
我相信你所要做的就是在调用脚本时命名参数,如下所示:
powershell.exe Path\ScripName -Param1 Value1 -Param2 Value2
Param1和Param2是函数签名中的实际参数名称。
祝您愉快!
-Command
参数或其别名-C
。test.ps1
,其中包含:function Get-Test() {
[cmdletbinding()]
Param (
[Parameter(Mandatory = $true, HelpMessage = 'The test string.')]
[String]$stringTest
)
Write-Host $stringTest
return
}
然后批处理文件将是:
rem Both commands are now working in both v5.1 and v7.1.
rem v7.1
"...pathto\pwsh.exe" -NoExit -Command ". '"...pathto\test.ps1"'; Get-Test ""help me"""
rem v5.1
powershell.exe -NoExit -Command ". '"...pathto\test.ps1"'; Get-Test ""help me"""
如果你的.ps1
文件路径中包含空格,那么在...pathto\test.ps1
周围加上引号是必须的。
同样适用于...pathto\pwsh.exe
这是我完整发布在Github上的问题:
'
包裹 ps 文件的路径,这样路径中的空格就不会阻止它的工作了。所以powershell.exe ". 'C:\path to\Test-Function.ps1'; Test-Me -Param1 'Hello world' -Param2 12345"
。 - Ste