如何从PowerShell写入.CMD文件? [英] How to write .CMD files from PowerShell?

查看:88
本文介绍了如何从PowerShell写入.CMD文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从PowerShell中写入有效的.CMD(或.BAT)文件?我正在使用> 运算符,但 cmd.exe 无法执行我创建的文件。

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.

以下是我正在尝试执行的示例。 [作为比较,我还从 CMD.EXE 写入.CMD文件,并显示它可以正常工作。

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]

在PowerShell中:

In PowerShell:

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

在PowerShell中写入.CMD文件:

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.

我怀疑 bar.cmd CMD.EXE 中使用调用不支持的编码创建的。 [尽管请注意,类型在以其当前编码显示 bar.cmd 的内容时没有问题。]

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.]

从PowerShell以编程方式写入.CMD文件的正确方法是什么,以便可以使用 CMD.EXE 调用该文件。 通话

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将默认为UTF- 16 LE。

PowerShell will default to UTF-16 LE.

短版。

sc bar.cmd '@set BAR=1' -en ASCII

这篇关于如何从PowerShell写入.CMD文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆