开发者

How to run a PowerShell script within a Windows batch file

开发者 https://www.devze.com 2022-12-26 13:42 出处:网络
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:

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:

  • Embedding SQL in a batch script using sqlcmd and a clever arrangements of goto's and comments at the beginning of the file
  • In a *nix environment having the name of the program you wish to run the script with on the first line of the script commented out, for example, #!/usr/local/bin/python.

There may not be a way to do this - in which case I will have to call the separate PowerShell script from the launching script.

One possible solution I've considered is to echo out the PowerShell script, and then run it. A good reason to not do this is that part of the reason to attempt this is to be using the advantages of the PowerShell environment without the pain of, for example, escape characters

I have some unusual constraints and would like to find an elegant solution. I suspect this question may be baiting responses of the variety: "Why don't you try and solve this different problem instead." Suffice to say these are my constraints, sorry about that.

Any ideas? Is there a suitable combination of clever comments and escape characters that will enable me to achieve this?

Some thoughts on how to achieve this:

  • A carat ^ at the end of a line is a continuation - like an underscore in Visual Basic
  • An ampersand & typically is used to separate commands echo Hello & echo World results in two echos on separate lines
  • %0 will give you the script that's currently running

So some开发者_C百科thing like this (if I could make it work) would be good:

# & call powershell -psconsolefile %0
# & goto :EOF
/* From here on in we're running nice juicy powershell code */
Write-Output "Hello World"

Except...

  • It doesn't work... because
  • the extension of the file isn't as per PowerShell's liking: Windows PowerShell console file "insideout.bat" extension is not psc1. Windows PowerShell console file extension must be psc1.
  • CMD isn't really altogether happy with the situation either - although it does stumble on '#', it is not recognized as an internal or external command, operable program or batch file.


This one only passes the right lines to PowerShell:

dosps2.cmd:

@findstr/v "^@f.*&" "%~f0"|powershell -&goto:eof
Write-Output "Hello World" 
Write-Output "Hello some@com & again" 

The regular expression excludes the lines starting with @f and including an & and passes everything else to PowerShell.

C:\tmp>dosps2
Hello World
Hello some@com & again


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.


Here the topic has been discussed. The main goals were to avoid the usage of temporary files to reduce the slow I/O operations and to run the script without redundant output.

And here's the best solution according to me:

<# :
@echo off
setlocal
set "POWERSHELL_BAT_ARGS=%*"
if defined POWERSHELL_BAT_ARGS set "POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%"
endlocal & powershell -NoLogo -NoProfile -Command "$input | &{ [ScriptBlock]::Create( ( Get-Content \"%~f0\" ) -join [char]10 ).Invoke( @( &{ $args } %POWERSHELL_BAT_ARGS% ) ) }"
goto :EOF
#>

param(
    [string]$str
);

$VAR = "Hello, world!";

function F1() {
    $str;
    $script:VAR;
}

F1;

An even better way (seen here):

<# : batch portion (begins PowerShell multi-line comment block)


@echo off & setlocal
set "POWERSHELL_BAT_ARGS=%*"

echo ---- FROM BATCH
powershell -noprofile -NoLogo "iex (${%~f0} | out-string)"
exit /b %errorlevel%

: end batch / begin PowerShell chimera #>

$VAR = "---- FROM POWERSHELL";
$VAR;
$POWERSHELL_BAT_ARGS=$env:POWERSHELL_BAT_ARGS
$POWERSHELL_BAT_ARGS

where POWERSHELL_BAT_ARGS are command line arguments first set as variable in the batch part.

The trick is in the batch redirection priority - this line <# : will be parsed like :<#, because redirection is with higher priority than the other commands.

But the lines starting with : in batch files are taken as labels - i.e., not executed. Still this remains a valid PowerShell comment.

The only thing left is to find a proper way for PowerShell to read and execute %~f0 which is the full path to the script executed by cmd.exe.


This seems to work, if you don't mind one error in PowerShell at the beginning:

dosps.cmd:

@powershell -<%~f0&goto:eof
Write-Output "Hello World" 
Write-Output "Hello World again" 


I like Jean-François Larvoire's solution very much, especially for his handling of Arguments and passing them to the powershell-script diredtly (+1 added).

But it has one flaw. AS I do npt have the reputatioin to comment, I post the correction as a new solution.

The script name as argument for Invoke-Expression in double-quotes will not work when the script-name contains a $-character, as this will be evaluated before the file contents is loaded. The simplest remedy is to replace the double quotes:

PowerShell -c ^"Invoke-Expression ('^& {' + [io.file]::ReadAllText('%~f0') + '} %ARGS%')"

Personally, I rather prefer using get-content with the -raw option, as to me this is more powershell'ish:

PowerShell -c ^"Invoke-Expression ('^& {' + (get-content -raw '%~f0') + '} %ARGS%')"

But that is, of course just my personal opinion. ReadAllText works just perfectly.

For completeness, the corrected script:

<# :# PowerShell comment protecting the Batch section
@echo off
:# Disabling argument expansion avoids issues with ! in arguments.
setlocal EnableExtensions DisableDelayedExpansion

:# Prepare the batch arguments, so that PowerShell parses them correctly
set ARGS=%*
if defined ARGS set ARGS=%ARGS:"=\"%
if defined ARGS set ARGS=%ARGS:'=''%

:# The ^ before the first " ensures that the Batch parser does not enter quoted mode
:# there, but that it enters and exits quoted mode for every subsequent pair of ".
:# This in turn protects the possible special chars & | < > within quoted arguments.
:# Then the \ before each pair of " ensures that PowerShell's C command line parser 
:# considers these pairs as part of the first and only argument following -c.
:# Cherry on the cake, it's possible to pass a " to PS by entering two "" in the bat args.
echo In Batch
PowerShell -c ^"Invoke-Expression ('^& {' + (get-content -raw '%~f0') + '} %ARGS%')"
echo Back in Batch. PowerShell exit code = %ERRORLEVEL%
exit /b

###############################################################################
End of the PS comment around the Batch section; Begin the PowerShell section #>

echo "In PowerShell"
$Args | % { "PowerShell Args[{0}] = '$_'" -f $i++ }
exit 0


Also consider this "polyglot" wrapper script, which supports embedded PowerShell and/or VBScript/JScript code; it was adapted from this ingenious original, which the author himself, flabdablet, had posted in 2013, but it languished due to being a link-only answer, which was deleted in 2015.

A solution that improves on Kyle's excellent answer:

Create a batch file (e.g. sample.cmd) with the following content:

<# ::
@echo off & setlocal
copy /y "%~f0" "%TEMP%\%~n0.ps1" >NUL && powershell -NoProfile -ExecutionPolicy Bypass -File "%TEMP%\%~n0.ps1" %*
set ec=%ERRORLEVEL% & del "%TEMP%\%~n0.ps1"
exit /b %ec%
#>

# Paste arbitrary PowerShell code here.
# In this example, all arguments are echoed.
'Args:'
$Args | % { 'arg #{0}: [{1}]' -f ++$i, $_ }

Note:

  • When the batch file runs, a temporary *.ps1 file that is cleaned up afterwards is created in the %TEMP% folder; doing so greatly simplifies passing arguments through (reasonably) robustly, simply by using %*
  • The above invokes Windows PowerShell. To call the cross-platform PowerShell (Core) v7+ edition, replace powershell with pwsh in the code above.

Explanation of the technique:

  • Line <# :: is a hybrid line that PowerShell sees as the start of a comment block, but cmd.exe ignores, a technique borrowed from npocmaka's answer.

  • The batch-file commands that start with @ are therefore ignored by PowerShell, but executed by cmd.exe; since the last @-prefixed line ends with exit /b, which exits the batch file right there, cmd.exe ignores the rest of the file, which is therefore free to contain non-batch-file code, i.e., PowerShell code.

  • The #> line ends the PowerShell comment block that encloses the batch-file code.

  • Because the file as a whole is therefore a valid PowerShell file, no findstr trickery is needed to extract the PowerShell code; however, because PowerShell only executes scripts that have filename extension .ps1, a (temporary) copy of the batch file must be created; %TEMP%\%~n0.ps1 creates the temporary copy in the %TEMP% folder named for the batch file (%~n0), but with extension .ps1 instead; the temporarily file is automatically removed on completion.

  • Note that 3 separate lines of cmd.exe statements are needed in order to pass the PowerShell command's exit code through.
    (Using setlocal enabledelayedexpansion hypothetically allows doing it as a single line, but that can result in unwanted interpretation of ! chars. in arguments.)


To demonstrate the robustness of the argument passing:

Assuming the code above has been saved as sample.cmd, invoking it as:

sample.cmd "val. w/ spaces & special chars. (\|<>'), on %OS%" 666 "Lisa \"Left Eye\" Lopez"

yields something like the following:

Args:
arg #1: [val. w/ spaces & special chars. (\|<>'), on Windows_NT]
arg #2: [666]
arg #3: [Lisa "Left Eye" Lopez]

Note how embedded " chars. were passed as \".
However, there are edge cases related to embedded " chars.:

:: # BREAKS, due to the `&` inside \"...\"
sample.cmd "A \"rock & roll\" life style"

:: # Doesn't break, but DOESN'T PRESERVE ARGUMENT BOUNDARIES.
sample.cmd "A \""rock & roll\"" life style"

These difficulties are owed to cmd.exe's flawed argument parsing, and ultimately it is pointless to try to hide these flaws, as flabdablet points out in his excellent answer.

As he explains, escaping the following cmd.exe metacharacters with ^^^ (sic) inside the \"...\" sequence solves the problem:

& | < >

Using the example above:

:: # OK: cmd.exe metachars. inside \"...\" are ^^^-escaped.
sample.cmd "A \"rock ^^^& roll\" life style"


This supports arguments unlike the solution posted by Carlos and doesn't break multi-line commands or the use of param like the solution posted by Jay. Only downside is that this solution creates a temporary file. For my use case that is acceptable.

@@echo off
@@findstr/v "^@@.*" "%~f0" > "%~f0.ps1" & powershell -ExecutionPolicy ByPass "%~f0.ps1" %* & del "%~f0.ps1" & goto:eof


Another sample batch+PowerShell script... It's simpler than the other proposed solution, and has characteristics that none of them can match:

  • No creation of a temporary file => Better performance, and no risk of overwriting anything.
  • No special prefixing of the batch code. This is just normal batch. And same thing for the PowerShell code.
  • Passes all batch arguments to PowerShell correctly, even quoted strings with tricky characters like ! % < > ' $
  • Double quotes can be passed by doubling them.
  • Standard input is usable in PowerShell. (Contrary to all versions that pipe the batch itself to PowerShell.)

This sample displays the language transitions, and the PowerShell side displays the list of arguments it received from the batch side.

<# :# PowerShell comment protecting the Batch section
@echo off
:# Disabling argument expansion avoids issues with ! in arguments.
setlocal EnableExtensions DisableDelayedExpansion

:# Prepare the batch arguments, so that PowerShell parses them correctly
set ARGS=%*
if defined ARGS set ARGS=%ARGS:"=\"%
if defined ARGS set ARGS=%ARGS:'=''%

:# The ^ before the first " ensures that the Batch parser does not enter quoted mode
:# there, but that it enters and exits quoted mode for every subsequent pair of ".
:# This in turn protects the possible special chars & | < > within quoted arguments.
:# Then the \ before each pair of " ensures that PowerShell's C command line parser 
:# considers these pairs as part of the first and only argument following -c.
:# Cherry on the cake, it's possible to pass a " to PS by entering two "" in the bat args.
echo In Batch
PowerShell -c ^"Invoke-Expression ('^& {' + [io.file]::ReadAllText(\"%~f0\") + '} %ARGS%')"
echo Back in Batch. PowerShell exit code = %ERRORLEVEL%
exit /b

###############################################################################
End of the PS comment around the Batch section; Begin the PowerShell section #>

echo "In PowerShell"
$Args | % { "PowerShell Args[{0}] = '$_'" -f $i++ }
exit 0

Note that I use :# for batch comments, instead of :: as most other people do, as this actually makes them look like PowerShell comments. (Or like most other scripting languages comments actually.)


Without fully understanding your question, my suggestion would be something like:

@echo off
set MYSCRIPT="some cool powershell code"
powershell -c %MYSCRIPT%

or better yet

@echo off
set MYSCRIPTPATH=c:\work\bin\powershellscript.ps1
powershell %MYSCRIPTPATH%


My current preference for this task is a polyglot header that works much the same way as mklement0's first solution:

<#  :cmd header for PowerShell script
@   set dir=%~dp0
@   set ps1="%TMP%\%~n0-%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.ps1"
@   copy /b /y "%~f0" %ps1% >nul
@   powershell -NoProfile -ExecutionPolicy Bypass -File %ps1% %*
@   del /f %ps1%
@   goto :eof
#>

# Paste arbitrary PowerShell code here.
# In this example, all arguments are echoed.
$Args | % { 'arg #{0}: [{1}]' -f ++$i, $_ }

I prefer to lay the cmd header out as multiple lines with a single command on each one, for a number of reasons. First, I think it's easier to see what's going on: the command lines are short enough not to run off the right of my edit windows, and the column of punctuation on the left marks it visually as the header block that the horribly abused label on the first line says it is. Second, the del and goto commands are on their own lines, so they will still run even if something really funky gets passed as a script argument.

I have come to prefer solutions that make a temporary .ps1 file to those that rely on Invoke-Expression, purely because PowerShell's inscrutable error messages will then at least include meaningful line numbers.

The time it takes to make the temp file is usually completely swamped by the time it takes PowerShell itself to lumber into action, and 128 bits worth of %RANDOM% embedded in the temp file's name pretty much guarantees that multiple concurrent scripts won't ever stomp each other's temp files. The only real downside to the temp file approach is possible loss of information about the directory the original cmd script was invoked from, which is the rationale for the dir environment variable created on the second line.

Obviously it would be far less annoying for PowerShell not to be so anal about the filename extensions it will accept on script files, but you go to war with the shell you have, not the shell you wish you had.

Speaking of which: as mklement0 observes,

# BREAKS, due to the `&` inside \"...\"
sample.cmd "A \"rock & roll\" life style"

This does indeed break, due to cmd.exe's completely worthless argument parsing. I've generally found that the less work I do to try to hide cmd's many limitations, the fewer unanticipated bugs I cause myself down the line (I am sure I could come up with arguments containing parentheses that would break mklement0's otherwise impeccable ampersand escaping logic, for example). Less painful, in my view, just to bite the bullet and use something like

sample.cmd "A \"rock ^^^& roll\" life style"

The first and third ^ escapes get eaten when that command line is initially parsed; the second one survives to escape the & embedded in the command line passed to powershell.exe. Yes, this is ugly. Yes, it does make it harder to pretend that cmd.exe isn't what gets first crack at the script. Don't worry about it. Document it if it matters.

In most real-world applications, the & issue is moot anyway. Most of what's going to get passed as arguments to a script like this will be pathnames that arrive via drag and drop. Windows will quote those, which is enough to protect spaces and ampersands and in fact anything other than quotes, which aren't allowed in Windows pathnames anyway.

Don't even get me started on Vinyl LP's, 12" turning up in a CSV file.


Use Invoke-Command (icm for short), we can prepend the following 4 line header to a ps1 file, make it a valid cmd batch:

<# : batch portion
@powershell -noprofile "& {icm -ScriptBlock ([Scriptblock]::Create((cat -Raw '%~f0'))) -NoNewScope -ArgumentList $args}" %*
@exit /b %errorlevel%
: end batch / begin powershell #>

"Result:"
$args | %{ "`$args[{0}]: $_" -f $i++ }

if want to make args[0] point to script path, change %* to "'%~f0'" %*


You can add three lines before your Powershell script, use block comments only and then save it as a batch file. Then, you can have a batch file to run the Powershell script. Example:

psscript.bat

@echo off
@powershell -command "(Get-Content -Encoding UTF8 '%0' | select-string -pattern '^[^@]')" | @powershell -NoProfile -ExecutionPolicy ByPass
@goto:eof
<# Must use block comment; Powershell script starts below #>
while($True) {
    Write-Host "wait for 3s"
    Start-Sleep -Seconds 3
}
0

精彩评论

暂无评论...
验证码 换一张
取 消