Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to run a PowerShell script within a Windows batch file
    text
    copied!<p>How do I have a PowerShell script embedded within the same file as a Windows batch script?</p> <p>I know this kind of thing is possible in other scenarios:</p> <ul> <li>Embedding SQL in a batch script using <code>sqlcmd</code> and a clever arrangements of goto's and comments at the beginning of the file</li> <li>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, <code>#!/usr/local/bin/python</code>.</li> </ul> <p>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.</p> <p>One possible solution I've considered is to echo out the PowerShell script, and then run it. A good reason to <em>not</em> 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, <a href="http://blogs.msdn.com/oldnewthing/archive/2009/10/29/9914426.aspx" rel="noreferrer">escape characters</a></p> <p>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.</p> <p>Any ideas? Is there a suitable combination of clever comments and escape characters that will enable me to achieve this?</p> <p>Some thoughts on how to achieve this:</p> <ul> <li>A carat <code>^</code> at the end of a line is a continuation - like an underscore in Visual Basic</li> <li>An ampersand <code>&amp;</code> typically is used to separate commands <code>echo Hello &amp; echo World</code> results in two echos on separate lines</li> <li>%0 will give you the script that's currently running</li> </ul> <p>So something like this (if I could make it work) would be good:</p> <pre class="lang-none prettyprint-override"><code># &amp; call powershell -psconsolefile %0 # &amp; goto :EOF /* From here on in we're running nice juicy powershell code */ Write-Output "Hello World" </code></pre> <p>Except...</p> <ul> <li>It doesn't work... because</li> <li>the extension of the file isn't as per PowerShell's liking: <code>Windows PowerShell console file "insideout.bat" extension is not psc1. Windows PowerShell console file extension must be psc1.</code></li> <li>CMD isn't really altogether happy with the situation either - although it does stumble on <code>'#', it is not recognized as an internal or external command, operable program or batch file.</code></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload