Batch file 尝试从批处理文件运行PowerShell脚本失败
以下内容正在生成异常:Batch file 尝试从批处理文件运行PowerShell脚本失败,batch-file,powershell,Batch File,Powershell,以下内容正在生成异常: & : The term '.\Run-Regression.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At l
& : The term '.\Run-Regression.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:3
+ & '.\Run-Regression.ps1' -InputCSV '..\Desktop\tests\V10MWB.csv' -CAR ...
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\Run-Regression.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
我做错了什么?和/或如何解决此问题
我确实希望保留相对路径,因为它具有其他依赖项
@ECHO OFF
:: Enable PowerShell script execution
PowerShell Set-ExecutionPolicy Unrestricted
:: Navigate to the 'Common' directory (preserves relative paths)
PUSHD %~dp0\..\Common
:: Prepare the 'logs' directory
IF NOT EXIST ..\logs (MD ..\logs)
DEL /Q ..\logs\*.log 1>NUL 2>&1
:: Execute script
PowerShell "& 'Run-Regression.ps1' -InputCSV '..\Desktop\tests\%1.csv' -CARS_ID 0 -RunOnDesktop -Log -Email -Progress -Archive 2>&1" 1>"..\logs\%1.log";
:: Navigate back to original directory
POPD
根据错误消息,在您调用脚本时,它无法在当前目录中找到脚本。请更改到正确的目录,或使用完全限定路径调用它。您的错误消息与批处理文件中的实际调用命令不匹配:
PowerShell“&运行回归.ps1”…”
失败,因为PowerShell by design不允许仅通过文件名从PowerShell内部运行可执行文件和脚本(无论是直接调用还是通过调用操作符&
)
相反,您必须在\
前面加上前缀,以明确表示要从当前目录运行脚本
如果*.ps1
实际上不在当前目录中,而是在批处理文件中,请参阅
但是,请考虑使用<代码>文件>代码>参数,而不是(隐含的)<代码>命令> /COD>参数,在这种情况下,不需要<代码> \\/Cord>前缀,并且简化了语法:
PowerShell -File Run-Regression.ps1 -InputCSV ..\Desktop\tests\%1.csv -CARS_ID 0 -RunOnDesktop -Log -Email -Progress -Archive 2>&1 1>"..\logs\%1.log";
注:
- 使用
和-File
之间有许多细微的区别;有关详细信息,请参阅-Command
- PowerShell[Core]的可执行文件名为
,默认为pwsh.exe
,而不是-File
,这是在类Unix平台上支持脚本所需的更改-Command
%~dp0
说明-它将指向批处理文件所在的文件夹。
例如,这将执行与bat\cmd文件位于同一文件夹中的Run Regression.ps1
脚本,而不考虑执行策略和启动文件夹
PowerShell.exe -ExecutionPolicy Bypass -File %~dp0Run-Regression.ps1
您可以在这个帖子中找到更有用的东西:感谢大家的回复,因为他们帮助我找到了以下解决方案,这些解决方案非常适合我的情况: PUSHD%~dp0..\Common PowerShell“&“%CD%”。\n运行Regression.ps1”。。。 流行音乐 再次感谢,
Allan G.检查给定的链接,您传递的参数错误是“运行回归.ps1”还是“.\Run回归.ps1”?@BernardMoeskops-感谢您提供的链接。正在审阅…如果“.\Run回归.ps1”不起作用,则是错误的目录。@AllanG我建议您不要将batch和Powershell混合使用,而是将整个内容写成Powershell。您仍然可以从资源管理器运行Powershell脚本。
PowerShell.exe -ExecutionPolicy Bypass -File %~dp0Run-Regression.ps1