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 commandsecho Hello & echo World
results in two echos on separate lines - %0 will give you the script that's currently running
So something 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.
It sounds like you're looking for what is sometimes called a "polyglot script". For CMD -> PowerShell,
If you don't need to support quoted arguments, you can even make it a one-liner:
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.
Without fully understanding your question, my suggestion would be something like:
or better yet
My current preference for this task is a polyglot header that works much the same way as mklement0's first solution:
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
andgoto
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 onInvoke-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 thedir
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,
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 likeThe 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 topowershell.exe
. Yes, this is ugly. Yes, it does make it harder to pretend thatcmd.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.Here the topic has been discussed. Main goals were to avoid the usage of temp files to reduce the slow IO operations and to run the script without redundant output.
And here's the best solution according to me:
Edit (a better way seen here )
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 prio 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.Another sample batch+PowerShell script... It's simpler than the other proposed solution, and has characteristics that none of them can match:
This sample displays the language transitions, and the PowerShell side displays the list of arguments it received from the batch side.
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.)
This one only passes the right lines to PowerShell:
dosps2.cmd
:The regular expression excludes the lines starting with
@f
and including an&
and passes everything else to PowerShell.