How to run a powershell script within a DOS batch file
Posted
by Don Vince
on Stack Overflow
See other posts from Stack Overflow
or by Don Vince
Published on 2010-04-09T18:43:05Z
Indexed on
2010/04/09
20:33 UTC
Read the original article
Hit count: 597
How do I have a powershell script embedded within the same file as a DOS batch script?
I know this kind of thing is possible in other scenarios:
- Embedding SQL in a DOS batch script using
sqlcmd
and a clever arrangements of goto's and comments at the beginning of the file - In a *nix environment having a the name of the program you wish to run the script with on the first line of the script commented out e.g.
#!/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 DOS 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, DOS 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 in DOS is a continuation - like an underscore in VB - An ampersand
&
in DOS typically is used to separate commandsecho Hello & echo World
results in 2 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.
- DOS isn't really altogether happy with the situation either - although it does stumble on
'#' is not recognized as an internal or external command, operable program or batch file.
© Stack Overflow or respective owner