开发者

Calling powershell function with parameter from .cmd or .bat file

开发者 https://www.devze.com 2023-01-16 07:41 出处:网络
I have written a powershell script which is a complete function taking parameters (e.g. function name (param) { } ) and below this is a call to the function, with the parameter.

I have written a powershell script which is a complete function taking parameters (e.g. function name (param) { } ) and below this is a call to the function, with the parameter.

I want to be able to call this function in its .ps1 file, passing in the parameter. How would I be able to package a c开发者_C百科all to the function via a .bat or .cmd file? I am using Powershell v2.0.


You should use so called "dot-sourcing" of the script and the command with more than one statement: dot-sourcing of the script + call of the function with parameters.

The test script Test-Function.ps1:

function Test-Me($param1, $param2)
{
 "1:$param1, 2:$param2"
}

The calling .bat file:

powershell ". .\Test-Function.ps1; Test-Me -Param1 'Hello world' -Param2 12345"

powershell ". .\Test-Function.ps1; Test-Me -Param1 \"Hello world\" -Param2 12345"

Notes: this is not a requirement but I would recommend enclosing the entire command text with double quotation marks escaping, if needed, inner quotation marks using CMD escape rules.


I believe all you have to do is name the parameters in the call to the script like the following:

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

Param1 and Param2 are actual parameter names in the function signature.

Enjoy!


To call a PowerShell function from cmd or batch with arguments you need to use the -Commmand Parameter or its alias -C.

Romans answer will work with PowerShell 5.1 for example but will fail for PowerShell 7.1.

Quote from an issue I left on GitHub on why the same command didn't work is:

So as to support Unix shebang lines, pwsh's CLI now defaults to the -File parameter (which expects only a script-file path), whereas powershell.exe default to -Command / -c. To make your commands work with pwsh, you must use -Command / -C explicitly.

So if you have a PowerShell file test.ps1 with:

function Get-Test() {
  [cmdletbinding()]
  Param (
    [Parameter(Mandatory = $true, HelpMessage = 'The test string.')]
    [String]$stringTest
    )
  Write-Host $stringTest
  return
}

And the batch file will then be:

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"""

The quotes around ...pathto\test.ps1 are a must if your .ps1 contains spaces.

The same goes for ...pathto\pwsh.exe


Here's the Github issue I posted in full:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消