breeves
breeves

Reputation: 23

How can I convert a multi-line batch file statement into Powershell?

I'm in the process of converting an old batch file to Powershell. In the batch file, the SET command is used to declare and set multiple variables, and then an executable is called that uses those variables, along with additional flags. How would I do this in Powershell?

Batch File code excerpt:

SET VAR1=VAL1
SET VAR2=VAL2
SET VAR3=VAL3
SET VAR4=VAL4
%DIRECTORY%\%SUBDIR%\EXECUTABLE.EXE -FLAG1 -FLAG2 -FLAG3

I first attempted to declare the Powershell variables and call the exe using Start-Process, but the executable is looking for specific variable names. I'm not sure if those variables can be seen by the exe in this scenario, but it doesn't work.

  $VAR1 = VAL1
  $VAR2 = VAL2
  $VAR3 = VAL3
Start-Process "$DRIVE\DIR\EXECUTABLE.exe -FLAG1 -FLAG2 -FLAG3"

I've also unsuccessfully attempted passing the multiple line command to the command shell:

$Command =  "CMD.exe /C 
             SET VAR1=VAL1
             SET VAR2=VAL2
             SET VAR3=VAL3
             SET VAR4=VAL4
             $DRIVE\$DIR\EXECUTABLE.exe -FLAG1 -FLAG2 -FLAG3
Invoke-Expression $Command

Note** The variables have to be set on multiple lines, even when I run the exe from a DOS prompt. Using the "&" (Batch) or ";" (Powershell) and passing all variables on one line doesn't work.

Upvotes: 2

Views: 134

Answers (1)

mklement0
mklement0

Reputation: 438323

  • For external programs (child processes) to see variables, they must be environment variables: use $env:VAR1 = 'VAL1' rather than $VAR1 = 'VAL1' - also note how the values must be quoted.

    • In cmd.exe (batch files), all variables are invariably also environment variables; in PowerShell, regular variables such as $VAR1 are visible only to the PowerShell session itself.
  • Do not use Start-Process to invoke external console applications, invoke them directly (synchronously, with standard streams connected to PowerShell's streams), using &, if the executable name/path is quoted and/or contains variable references; do not quote the command line as a whole; specify and - if necessary - quote the executable name/path and arguments individually.
    Similarly, Invoke-Expression should generally be avoided.

Therefore:

  $env:VAR1 = 'VAL1'
  $env:VAR2 = 'VAL2'
  $env:VAR3 = 'VAL3'
  & "$DRIVE\DIR\EXECUTABLE.exe" -FLAG1 -FLAG2 -FLAG3

Upvotes: 2

Related Questions