运行 Powershell 中的 .cmd/.bat 脚本

Running .cmd/.bat script in Powershell

我正在尝试在 powershell 中编写和执行 .cmd 脚本。我的代码是:

$script = @'
@echo off
SETLOCAL

CALL something here
'@

Invoke-Expression -Command: $script

这是基于 this link which explains the here string in powershell. It's at the bottom of the link. Here's the related msdn.

谨此another related link 致试图做同样事情的人。

我不断收到与在字符串中包含“@”运算符有关的错误:

Invoke-Expression : At line:1 char:7
+ @echo off
+       ~~~
Unexpected token 'off' in expression or statement.
At line:1 char:1
+ @echo off
+ ~~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@echo' can be used only as an argument to a command. To reference variables in an expression use '$echo'.

我试过转义“@”符号和许多其他东西。我想知道为什么它似乎在第三个 link 中对他们有用,但在我的情况下会抛出此错误。

编辑: 写入 .bat 文件然后 运行 bat 文件导致相同的错误:

$batchFileContent = @'
@echo off
c:\windows\system32\ntbackup.exe backup "C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\Windows NT\NTBackup\data\chameme.bks" /n "1file.bkf1 created 06/09/2013 at 09:36" /d "Set created 06/09/2013 at 09:36" /v:no /r:no /rs:no /hc:off /m normal /j chameme /l:s /f "\fs1\Exchange Backups$file.bkf"
'@

$batchFileContent | Out-File -LiteralPath:"$env:TEMP\backup.cmd" -Force

Invoke-Expression -Command:"$env:TEMP\backup.cmd"

Remove-Item -LiteralPath:"$env:TEMP\backup.cmd" -Force

正如 Bill Stewart 指出的那样,我应该在 powershell 中编写 .cmd 脚本的内容。

编辑: 这个

$script = @'
cmd.exe /C "@echo off"
cmd.exe /C "SETLOCAL"

cmd.exe /C "CALL something here"
'@

Invoke-Expression -Command: $script

似乎有效。

发生这种情况是因为 Invoke-Expression 使用 PowerShell 解释您的字符串。 PowerShell 允许您执行 运行 shell 命令,但它首先将事物解释为 PowerShell。 @ 字符是 PowerShell 中的展开运算符。

您应该将命令保存在批处理文件中,然后执行。

或者您可以通过 shell 输出到 cmd.exe:

来执行单行命令
Invoke-Expression "cmd.exe /c @echo something"