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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With