批处理调用PowerShell报错:-command未被识别问题求助
问题分析
嘿,这报错的根源其实是批处理变量定义时的一个小坑——等号两边的空格不能乱加!你写的set PWSH = %SystemRoot%\...,会让批处理把变量名识别成PWSH (注意末尾带空格),而不是你想要的PWSH。当你调用%PWSH%的时候,这个变量实际上是空的,相当于直接执行-command ...,系统找不到这个命令,自然就报“-command不是内部或外部命令”的错了。
另外提个小细节,你最后一行的if errorlevel 1 exit %errorlevel%,用exit /b %errorlevel%会更合适,因为exit会直接关掉整个命令行窗口,而exit /b只会退出当前批处理脚本,双击运行的时候体验更好。
可行解决方案
方案1:修正变量定义的空格问题
把变量定义行的空格删掉,这是最直接的修复方式:
@echo off set PWSH=%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe %PWSH% -command $input ^| %1\post-commit-jenkins.ps1 %1 %2 pause if errorlevel 1 exit /b %errorlevel%
方案2:直接调用powershell(简化写法)
如果这个变量不需要复用,也可以直接写死powershell的路径,彻底避开变量定义的问题:
@echo off %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -command $input ^| %1\post-commit-jenkins.ps1 %1 %2 pause if errorlevel 1 exit /b %errorlevel%
验证小技巧
要是你不确定变量是否正确加载,可以在批处理里加一行echo %PWSH%来测试:
@echo off set PWSH=%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe echo 当前PWSH变量值:%PWSH% %PWSH% -command $input ^| %1\post-commit-jenkins.ps1 %1 %2 pause if errorlevel 1 exit /b %errorlevel%
运行后如果能显示powershell的完整路径,说明变量定义没问题啦。
内容的提问来源于stack exchange,提问作者Abhishek Kumar
相关产品推荐
相关产品推荐

