简体   繁体   中英

How to pass a parameter from Batch file to a function inside a Powershell script

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?

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

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

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.

在我看来,你应该选择使用什么 - 批处理文件或PowerShell :) PowerShell功能更强大,但批处理文件更容易创建(特别是使用Dr.Batcher )并且可以在任何地方运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM