windowspowershellbatch-filecmdscripting

How to run a PowerShell script within a Windows batch file


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:

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:

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...


Solution

  • 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