在运行时将值传递给Powershell的批处理文件

时间:2017-08-08 08:42:26

标签: powershell batch-file

我有一个powershell脚本P.ps1,它在内部调用批处理脚本B1.batB2.bat

P.ps1代码如下:

B1.bat
$a= Read-host "Choose 1 or 2:"
B2.bat
Write-host "End of code"

B1.bat代码是:

echo "Hello World"

B2.bat需要来自powershell script.i.e的输入。必须将$a发送至B2.bat

@ECHO OFF
SET var = a 
rem This "a" is coming from "P.ps1"
ECHO We're working with %var%

2 个答案:

答案 0 :(得分:1)

您可以在PowerShell脚本中使用此变量,如下所示:

B1.bat
$a= Read-host "Choose 1 or 2:"
B2.bat $a
Write-host "End of code"

然后在批处理脚本中执行此操作:

@ECHO OFF
SET a=%1
rem This "a" is coming from "P.ps1"
ECHO We're working with %a%

使用%1引用通过命令行传递的第一个变量,使用%2表示第二个变量,%3表示第三个变量,依此类推。

答案 1 :(得分:0)

由于B1.batB2.bat继承了P.ps1的环境,您可以在$Env:Var=$a中使用P.ps1

PS> gc .\B1.bat
@Echo "Hello World"

PS> gc .\B2.bat
@ECHO OFF
ECHO We're working with %var%

PS> gc .\p.ps1
.\B1.bat
$a = Read-host "Choose 1 or 2 "
$Env:var=$a
.\B2.bat
Write-host "End of code"

PS> .\p.ps1
"Hello World"
Choose 1 or 2 : 1
We're working with 1
End of code
相关问题