Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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 call to the function via a .bat or .cmd file? I am using Powershell v2.0.

like image 884
GurdeepS Avatar asked Sep 14 '10 19:09

GurdeepS


People also ask

Can you call PowerShell from a batch file?

PowerShell.exe can of course be called from any CMD window or batch file to launch PowerShell to a bare console like usual. You can also use it to run commands straight from a batch file, by including the -Command parameter and appropriate arguments.

How do I pass parameters to a PowerShell script?

How do I pass parameters to PowerShell scripts? Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.

How do I run a PowerShell script in a .cmd script?

Running a PowerShell script from the Command Prompt If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1. PowerShell -File C:\TEMP\MyNotepadScript.

Can batch file take parameters?

Batch parameters (Command line parameters): In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on. If you require all arguments, then you can simply use %* in a batch script.


1 Answers

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.

like image 89
Roman Kuzmin Avatar answered Oct 10 '22 08:10

Roman Kuzmin