从 .cmd 或 .bat 文件中调用带参数的 Powershell 函数

10

我写了一个完整的 PowerShell 脚本,其中包含一个带参数的函数(例如:function name (param) { } ),在此之下是对该函数的调用,同时带上参数。

我想能够在 .ps1 文件中调用此函数,并传入参数。如何通过 .bat 或 .cmd 文件打包调用这个函数?我使用的是 Powershell v2.0。

3个回答

17

您应该使用所谓的“点源”脚本和带有多个语句的命令:脚本的点源 + 带参数的函数调用。

测试脚本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转义规则并用双引号将整个命令文本括起来,我建议这样做。


这个很好用。只需要用 ' 包裹 ps 文件的路径,这样路径中的空格就不会阻止它的工作了。所以 powershell.exe ". 'C:\path to\Test-Function.ps1'; Test-Me -Param1 'Hello world' -Param2 12345" - Ste

0

我相信你所要做的就是在调用脚本时命名参数,如下所示:

powershell.exe Path\ScripName -Param1 Value1 -Param2 Value2

Param1和Param2是函数签名中的实际参数名称。

祝您愉快!


2
我该如何调用实际函数呢?这会调用我的函数吗?如果在同一个.ps1文件中有>1个具有参数签名的函数怎么办? - GurdeepS

0
要从cmd或批处理中调用带有参数的PowerShell函数,您需要使用-Command参数或其别名-C
例如,罗曼的答案适用于PowerShell 5.1,但对于PowerShell 7.1则会失败。
我在GitHub上留下的问题中引用的一句话是:
为了支持Unix shebang行,pwsh的CLI现在默认使用-File参数(它只期望一个脚本文件路径),而powershell.exe默认使用-Command / -c。为了使您的命令与pwsh配合工作,您必须显式地使用-Command / -C。
因此,如果您有一个PowerShell文件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上的问题:

https://github.com/PowerShell/PowerShell/issues/15281


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接