如何在没有外部ps1文件的情况下创建一个执行powershell脚本的bat文件



双击此处查找时,存在如何运行ps1文件的问题。但是,我想知道是否有一个解决方案不需要两个单独的文件。

一种方法是将Powershell脚本嵌入到带有echos和注释的.bat文件中:

echo `
REM | Out-Null <#
powershell.exe -ExecutionPolicy Bypass -Command "iex ((Get-Content "%~f0") -join "`n") | Out-Null"
goto :eof
#>
(powershell script here)
<#
:eof
::#>

这会在控制台输出中产生一些工件,但脚本成功地嵌入在bat文件中运行。由于"echo"既是Windows命令行命令,也是Powershell命令,因此它可以正常工作而不会出错。

编辑:几年后,我有了一个改进的版本:

@powershell.exe -ExecutionPolicy Bypass -Command "$_=((Get-Content "%~f0") -join "`n");iex $_.Substring($_.IndexOf("goto :"+"EOF")+9)"
@goto :EOF
(powershell script here)

改进:

  • 只需要2行文件头(我不知道:EOF(
  • 没有控制台输出,除非您从脚本中这样做
  • 由于仅将实际脚本内容传递给powershell.exe,因此与Write-Output兼容

相关内容

最新更新