簡體   English   中英

如何在沒有外部 ps1 文件的情況下創建一個執行 powershell 腳本的 bat 文件?

[英]How do I create a bat file that executes powershell script without an external ps1 file?

當您雙擊找到此處時,存在一個關於如何運行 ps1 文件的現有問題。 但是我想知道是否有不需要 2 個單獨文件的解決方案。

一種方法是將 Powershell 腳本嵌入到帶有回聲和注釋組合的 .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兼容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM