2017-08-08 118 views
2

我有一個powershell腳本P.ps1,它在內部調用批處理腳本B1.batB2.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% 

回答

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。依此類推。

+0

使用$Env:Var=$a在批處理不要把空格等號周圍的一組命令。空格將成爲變量名稱和內容的一部分。 – LotPings

+0

哦,謝謝!我會編輯。 –

0

由於B1.batB2.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