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.
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With