从批处理文件运行Powershell
我正在.bat文件中尝试这些命令从批处理文件运行Powershell,powershell,batch-file,command,Powershell,Batch File,Command,我正在.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; }" 但这会抛出一个错
@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语法如下所示:
$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 }}"
是的,空白是问题所在。非常感谢!检查以下答案:
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 }}"