在运行时将值传递给Powershell的批处理文件
问题描述:
我有一个powershell脚本P.ps1
,它在内部调用批处理脚本B1.bat
和B2.bat
。在运行时将值传递给Powershell的批处理文件
P.ps1
代码如下:
B1.bat
$a= Read-host "Choose 1 or 2:"
B2.bat
Write-host "End of code"
B1.bat
代码是:从的powershell script.i.e
echo "Hello World"
B2.bat
需要输入。 $a
已被发送到B2.bat
@ECHO OFF
SET var = a
rem This "a" is coming from "P.ps1"
ECHO We're working with %var%
答
你会使用变量的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。依此类推。
答
由于B1.bat
和B2.bat
继承P.ps1
环境,你可以简单地在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
使用
$Env:Var=$a
在批处理不要把空格等号周围的一组命令。空格将成为变量名称和内容的一部分。 – LotPings哦,谢谢!我会编辑。 –