【问题标题】:How do I create a bat file that executes powershell script without an external ps1 file?如何在没有外部 ps1 文件的情况下创建执行 powershell 脚本的 bat 文件?
【发布时间】:2026-01-18 20:15:01
【问题描述】:

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

【问题讨论】:

  • 在回答您的具体问题时,是的。
  • 批处理文件可以运行powershell并给它一个脚本块来执行。
  • 这绝对是一个重复的问题。已经有几个关于这个的问题了。
  • 您可以在this topic查看将 PS 代码嵌入到批处理文件中的简单方法。

标签: windows powershell batch-file


【解决方案1】:

一种方法是将 Powershell 脚本嵌入到带有 echos 和 cmets 组合的 .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
  • 除非您从脚本中这样做,否则没有控制台输出
  • Write-Output 兼容,因为只将实际脚本内容传递给powershell.exe

【讨论】:

  • 一项增强功能:代替@goto :EOF,我使用exit %ERRORLEVEL%$_.IndexOf('exit' + ' ') 来允许传播退出代码。
最近更新 更多