How to run a PowerShell script within a Windows batch file

前端 未结 10 1929
半阙折子戏
半阙折子戏 2020-11-27 16:22

How do I have a PowerShell script embedded within the same file as a Windows batch script?

I know this kind of thing is possible in other scenarios:

  • Em
10条回答
  •  失恋的感觉
    2020-11-27 16:55

    It sounds like you're looking for what is sometimes called a "polyglot script". For CMD -> PowerShell,

    @@:: This prolog allows a PowerShell script to be embedded in a .CMD file.
    @@:: Any non-PowerShell content must be preceeded by "@@"
    @@setlocal
    @@set POWERSHELL_BAT_ARGS=%*
    @@if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
    @@PowerShell -Command Invoke-Expression $('$args=@(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join([char]10,$((Get-Content '%~f0') -notmatch '^^@@'))) & goto :EOF
    

    If you don't need to support quoted arguments, you can even make it a one-liner:

    @PowerShell -Command Invoke-Expression $('$args=@(^&{$args} %*);'+[String]::Join([char]10,(Get-Content '%~f0') -notmatch '^^@PowerShell.*EOF$')) & goto :EOF
    

    Taken from http://blogs.msdn.com/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx. That was PowerShell v1; it may be simpler in v2, but I haven't looked.

提交回复
热议问题