views:

2113

answers:

3

I have a Batch file which will call a Powershell Script :

BATCH FILE : @ECHO OFF powershell ..\PowerShellScript.ps1

The powershell script in turn has a function which expects a parameter :

POWERSHELL SCRIPT:

function PSFunction([string]$Parameter1)
{
Write-Host $Parameter1
}

Lets say i have a value : VALUE1 which needs to be passed from the batch File while calling the PowerShellScript.ps1, how do I pass it to the function PSFunction so that my output is VALUE1?

+3  A: 

modify your script to look like the following

function PSFunction([string]$Parameter1)
{
  Write-Host $Parameter1
}

PSFunction $args[0]

and from the batch file, it would look like

powershell ..\PowerShellScript.ps1 VALUE1
Scott Weinstein
and how do I pass the parameter value "VALUE1" from the Batch file ?
Murtaza RC
see updated answer
Scott Weinstein
+2  A: 

Defining a function in a Powershell script does not execute the function. If you want that, then your script might need to look like that:

function PSFunction([string]$Parameter1)
{
  Write-Host $Parameter1
}
PSFunction "some string"

From within the script you still have a dynamic $args variable that gets any parameters you passed to the script. So

function PSFunction([string]$Parameter1)
{
  Write-Host $Parameter1
}
PSFunction $args[0]

will pass the first parameter you gave on the commandline on to the function.

Joey
+2  A: 

Use the -Command switch to tell powershell.exe to interpret a string as if it were typed at a PowerShell prompt. In your case, the string could dot-source PowerShellScript.ps1 (to import it into the new powershell.exe environment) and then call PSFunction with VALUE1 as a parameter:

set VALUE1=Hello World
powershell.exe -command ". ..\PowerShellScript.ps1; PSFunction '%VALUE1%'"
totorocat