运行 来自批处理文件的 Powershell

Running Powershell from a Batch File

我正在 .bat 文件中尝试这些命令

@echo off & setLocal EnableDelayedExpansion

powershell -NoLogo -NoProfile -Command ^    
    "$h = [int](Get-Date -Format "HH");" ^
    "$diff = (7-$h)*3600;" ^
    "if ($h -le 7 -or $h -ge 0) { ECHO $h; ECHO $diff; }"

但这会引发一个错误,提示无法识别命令。这里我试图获取小时数并从 7 中减去 $h。然后将结果乘以 3600 并在控制台上打印它。

谁能告诉我我做错了什么?

脱字符 ^ 必须是续行中的最后一个字符。在代码中,第一行有一些尾随空格。

考虑包含空格的代码,通过在行首和行尾添加管道字符来说明。

|powershell -NoLogo -NoProfile -Command ^    |
|    "$h = [int](Get-Date -Format "HH");" ^|
|    "$diff = (7-$h)*3600;" ^|
|    "if ($h -le 7 -or $h -ge 0) { ECHO $h; ECHO $diff; }"|

运行 这提供了以下输出:

C:\Temp>t.cmd
Cannot process the command because of a missing parameter. A command must follow -Command.

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
...
'"$h = [int](Get-Date -Format "HH");"' is not recognized as an internal or external command, operable program or batch file.

虽然删除尾随空格的工作方式与此类似, |powershell -NoLogo -NoProfile -Command ^| ...

C:\Temp>t.bat
10
-10800

正确的 powershell 语法如下所示:

$h = [int](Get-Date -Format "HH")
    $diff = (7-$h)*3600
    if ($h -le 7 -or $h -ge 0) { 
        write-output $h 
        write-output $diff
    }

您可以将此 powershell 代码保存为 ps.1 文件并从批处理文件中调用它

尝试 运行 它们在一行中:

powershell -NoLogo -NoProfile -Command "& {    $h = [int](Get-Date -Format 'HH'); $diff = (7-$h)*3600; if ($h -le 7 -or $h -ge 0) { Write-Output $h; Write-Output $diff }}"