0

For some reason i simply can't understand most of the sites who explain this question. So i'll try to ask here, if i'm am in the wrong place, just tell me in the comments and i'll put this in another forum and delete this question.

Let's say that i have 2 files, Batch.bat and PowerShell.ps1.

Batch.bat:

set A="ThisIsSuchVar!"

PowerShell.ps1:

$B = "Well, i don't know what to do here"

What can i do to the B variable be the same as the A variable?

Remember: I want the Batch variable to go to the PowerShell file. It's an one-way script. I want to use the built-in windows sources. And please, consider that i am a complete newbie in programming and don't speak english very well, so be the simplest possible, please.

Walter Mitty
  • 18,205
  • 2
  • 28
  • 58
ArsonFG
  • 315
  • 8
  • 22
  • 1
    Are you calling Powershell.ps1 from Batch.bat? – Gerald Schneider Feb 05 '16 at 12:54
  • 1
    You could set an environment variable in batch to be read by PowerShell or (simpler) configure the PowerShell script to accept the batch variable as an argument. In the case of the latter you wont have to worry about cleaning up variables or session states. – Matt Feb 05 '16 at 12:54
  • Title is a little misleading but this post should get you started: http://stackoverflow.com/questions/932291/calling-powershell-cmdlets-from-windows-batch-file – Matt Feb 05 '16 at 12:58
  • 1
    Related: you might be interested in playing with [Batch + PowerShell polyglots](http://www.dostips.com/forum/viewtopic.php?p=45095#p45095). – rojo Feb 06 '16 at 03:10

1 Answers1

6

In your batch file run.bat, set the environment variable A and run the PowerShell script:

set A=8
PowerShell.exe -File .\script.ps1
pause

In script.ps1, get the environment variable A, and assign its value to B:

$B=$Env:A
echo $B

When you run run.bat you get:

C:\Temp\try>set A=8

C:\Temp\try>PowerShell.exe -File .\script.ps1
8

C:\Temp\try>pause
Press any key to continue . . .
Adi Levin
  • 5,165
  • 1
  • 17
  • 26
  • @PetSerAI For some reason my script get stuck before the `pause`. It says the `C:\Temp\try>PowerShell.exe -File .\script.ps1 8` and simply stop. Can you tell me why? – ArsonFG Feb 05 '16 at 14:41
  • @AdiLevin Nope, it doesn't read the `pause` line, it stops in the `C:\Temp\try>PowerShell.exe -File .\script.ps1 8` – ArsonFG Feb 05 '16 at 15:21
  • Just stop, don't do anything else, the window stay there, the PowerShell doesn't do anything... – ArsonFG Feb 05 '16 at 15:22
  • Ooh, sorry! Forgive me, my fault, your script is working perfectly, i just wrote it wrong. – ArsonFG Feb 06 '16 at 00:19