Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter from a batch file to a PowerShell script

In my batch file, I call the PowerShell script like this:

powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1" 

Now, I want to pass a string parameter to START_DEV.ps1. Let's say the parameter is w=Dev.

How can I do this?

like image 292
Karan Avatar asked Jun 15 '11 14:06

Karan


People also ask

How do you pass parameters in PowerShell script?

A default value will not work with a mandatory parameter. You can omit the =$true for advanced parameters of type boolean [Parameter(Mandatory)] . @Andrew First of all you have to change the type of the parameter to [string] . If you then want to pass a string as parameter you can use either ' or " .

Can I run a PowerShell script from a batch file?

Use the -File Parameter to Run a PowerShell Script From a Batch File. You can invoke a PowerShell script using the -File parameter. It is the simple command to run a PowerShell script from the command prompt.


2 Answers

Let's say you would like to pass the string Dev as a parameter, from your batch file:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev" 

put inside your powershell script head:

$w = $args[0]       # $w would be set to "Dev" 

This if you want to use the built-in variable $args. Otherwise:

 powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\"" 

and inside your powershell script head:

param([string]$Environment) 

This if you want a named parameter.

You might also be interested in returning the error level:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE" 

The error level will be available inside the batch file as %errorlevel%.

like image 122
Emiliano Poggi Avatar answered Oct 18 '22 20:10

Emiliano Poggi


Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w) Write-Output $w 

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String" 

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

like image 42
ravikanth Avatar answered Oct 18 '22 20:10

ravikanth