Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write .CMD files from PowerShell?

Tags:

powershell

cmd

How does one write to a valid .CMD (or .BAT) file from PowerShell? I'm using the > operator but cmd.exe can't execute the files I create.

Below is an example of what I'm trying to do. [For comparison, I also write to a .CMD file from CMD.EXE and show that it works fine]

In PowerShell:

PS C:\> "@set BAR=1" > bar.cmd  // write to a .CMD file from PowerShell

In CMD.EXE:

C:\> echo @set FOO=1 > foo.cmd  // write to a .CMD file from CMD.EXE
C:\> type foo.cmd               // display .CMD file written from CMD.EXE
@set FOO=1                      // PASS
C:\> type bar.cmd               // display .CMD file written from PowerShell
@set BAR=1                      // PASS
C:\> call foo.cmd               // invoke .CMD file written from CMD.EXE
C:\> echo %FOO%
1                               // PASS
C:\> call bar.cmd               // invoke .CMD file written from PowerShell
C:\> ■@                         // FAIL
'■@' is not recognized as an internal or external command,
operable program or batch file.

I suspect that bar.cmd is being created with an encoding not support by call in CMD.EXE. [Although notice that type has no problem displaying the contents of bar.cmd in its current encoding.]

What's the proper way to programmatically write to a .CMD file from PowerShell such that it can be invoked from CMD.EXE with call?

like image 996
jwfearn Avatar asked Mar 13 '11 03:03

jwfearn


1 Answers

Set-Content bar.cmd '@set BAR=1' -Encoding ASCII

PowerShell will default to UTF-16 LE.

Short version.

sc bar.cmd '@set BAR=1' -en ASCII
like image 135
JasonMArcher Avatar answered Oct 27 '22 13:10

JasonMArcher