在Powershell中执行批处理文件

2024-04-21

我想从批处理文件执行以下命令:

"C:\OpenCover\tools\OpenCover.Console.exe" -register:user -target:"%VS110COMNTOOLS%..\IDE\mstest.exe" -targetargs:"/testcontainer:\"C:\Develop\bin\Debug\MyUnitTests.dll\" ... "
PAUSE

现在我想将进程的输出记录到一个文件中,我遇到了非常方便的 powershell 使用方法

powershell "dir | tee output.log"

但这并不将我的批处理文件作为第一个参数(powershell "my.bat | tee output.log") 因为它不是 cmdlet、函数或脚本文件的名称。

我可以更改我的批处理文件,也就是说powershell "OpenCover.Console.exe..."但我必须调整所有引号并更改转义字符等等。

有没有办法让批处理文件在powershell中执行?或者有没有一种方法可以在执行某些 powershell 命令后将我的行从批处理中保持不变,并且全部执行“就像应该那样”?


Unless your batch file is in a folder in the %PATH%, PowerShell won't find it [1], so you'll have to supply an explicit file path (whether relative or absolute).

例如,如果批处理文件位于当前文件夹中,请运行:

powershell -c ".\my.bat | tee output.log"

Consider adding -noprofile to suppress loading of the profile files, which is typically only needed in interactive sessions.

如果批处理文件路径包含嵌入空格,请将其用单引号括起来并在前面添加&:

powershell -c "& '.\my script.bat' | tee output.log"

注意:我特意添加了-c(短缺:-Command) 上面的参数名称;尽管powershell.exe - Windows PowerShell- 默认为该参数,但在以下情况下不再适用PowerShell [核心] v6+(其可执行文件名称是pwsh), 在哪里-File现在是默认值 - 请参阅about_PowerShell.exe https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_PowerShell.exe and about_pwsh https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh


[1] More accurately, PowerShell - unlike cmd.exe - will by design not execute scripts in the current folder by their mere filename (in an interactive PowerShell session you'll get a hint to that effect). This is a security feature designed to prevent accidental invocation of a different executable than intended.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Powershell中执行批处理文件 的相关文章

随机推荐