[英]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 语法如下所示:
$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) { 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.