Reputation: 1330
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:
sqlcmd
and a clever arrangements of goto's and comments at the beginning of the file#!/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:
^
at the end of a line is a continuation - like an underscore in Visual Basic&
typically is used to separate commands echo Hello & echo World
results in two echos on separate linesSo 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...
Windows PowerShell console file "insideout.bat" extension is not psc1. Windows PowerShell console file extension must be psc1.
'#', it is not recognized as an internal or external command, operable program or batch file.
Upvotes: 25
Views: 38557
Reputation: 483
I currently use this method that I developed. Although it is not "as short" as the others, it has the advantage of not using anything that can be "fixed" at some point:
@Echo Off & Set "_F0=%~f0" & Title ...
PowerShell.exe -NoProfile -Command "Set-Content -LiteralPath $Env:Temp\_.ps1 -Value ([RegEx]::Matches([System.IO.File]::ReadAllText($Env:_F0), '(?smi)^(Pause|Exit)(.*)$').Groups[2].Value) -Encoding Unicode -Force"
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -File "%Temp%\_.ps1"
Exit
Remove-Item -LiteralPath $Env:Temp\_.ps1 -Force
It works like this:
%Temp%_\.ps1
with everything below the first line that starts with Pause
or Exit
. Set-Content
is used to force the replacement if the file already exists, is in read-only mode, or is hidden. In addition, Set-Content
does not have the "large lines" problem that Out-File
can have..ps1
into memory, it becomes completely unnecessary to keep the file while the script is running.Below is the version I use to run as administrator:
@Echo Off & Set "_F0=%~f0" & Title ...
PowerShell.exe -NoProfile -Command "Set-Content -LiteralPath $Env:Temp\_.ps1 -Value ([RegEx]::Matches([System.IO.File]::ReadAllText($Env:_F0), '(?smi)^(Pause|Exit)(.*)$').Groups[2].Value) -Encoding Unicode -Force"
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -File "%Temp%\_.ps1"
Exit
Function Del-PS1 {Remove-Item -LiteralPath $Env:Temp\_.ps1 -Force}
If ((Get-Item -LiteralPath 'Registry::HKU\S-1-5-19' -ErrorAction SilentlyContinue)) {Del-PS1} Else {
Try {Start-Process -FilePath PowerShell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$Env:Temp\_.ps1`"" -Verb RunAs} Catch {Del-PS1}
Exit
}
$Host.UI.RawUI.WindowTitle = '...'
Upvotes: 0
Reputation: 437052
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
set "__thisBatchFile=%~f0"
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.
# Use $env:__thisBatchFile to determine this batch file's full path.
'Args:'
$Args | % { 'arg #{0}: [{1}]' -f ++$i, $_ }
Note:
*.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 %*
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"
Upvotes: 5
Reputation: 1614
Okay, so I take 1% credit for this, but I wanted to contribute to a thread I have come back to time and time again. This is a matured culmination of all of the snippets above, effectively addressing all of the different bugs I am aware of. I built this to make launching PowerShell scripts easier within our organization.
UPDATE: I use this polyglot script for basically all the scripts we utilize within the domain to simplify script running. As such, I added some functions to help improve execution consistency leveraging what batch is better than PowerShell at.
<# :: Start of the PS comment around the Batch Section ###########################################################
@ECHO OFF
:# Disabling argument expansion avoids issues with ! in arguments.
SetLocal EnableExtensions DisableDelayedExpansion
:# Temporarily Ignore Zone Checking
SET "SEE_MASK_NOZONECHECKS=1"
:# Define Intial Variable(s)
FOR %%V in (noCLS noWait isUNC didTimeout NoAdmin) DO (SET "%%V=FALSE")
SET "ARGS=%*" & SET "startDir=%cd%" & SET "scriptDir=%~dp0" & SET "FilePath=%~f0"
:# Extract Non-PowerShell Variables.
ECHO. %ARGS% | Findstr /I /C:" \?NoCLS">nul && (SET "NoCLS=TRUE" & SET "ARGS=%ARGS:?NoCLS =%")
ECHO. %ARGS% | Findstr /I /C:" \?NoWait">nul && (SET "NoWait=TRUE" & SET "ARGS=%ARGS:?NoWait =%")
ECHO. %ARGS% | Findstr /I /C:" \?NoAdmin">nul && (SET "NoAdmin=TRUE" & SET "ARGS=%ARGS:?NoAdmin =%")
:# Prepare the batch arguments, so that PowerShell parses them correctly
IF defined ARGS set ARGS=%ARGS:"=\"%
IF defined ARGS set ARGS=%ARGS:'=''%
:# Enforce Elevation If Required.
IF "%NoAdmin%" == "FALSE" (
net session >nul 2>&1 || (
ECHO. Script requires elevation
pause >nul
EXIT /B 1
)
)
:# Ensure path is utilizing a lettered drive path.
IF "%FilePath:~0,2%" == "\\" DO (
PUSHD "%~dp0"
SET "isUNC=True"
) Else (
If NOT "%scriptDir%" == "%startDir" (
CD /D "%~dp0"
)
)
SET "FilePath=%CD%\%~nx0"
:# Escape the file path for all possible invalid characters.
SET "FilePath=%FilePath:'=''%"
SET "FilePath=%FilePath:^=^^%"
SET "FilePath=%FilePath:[=`[%"
SET "FilePath=%FilePath:]=`]%"
SET "FilePath=%FilePath:&=^&%"
:# ============================================================================================================ #:
:# 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; Entering PowerShell.
"%WinDir%\System32\WindowsPowerShell\v1.0\powershell.exe" -c ^
^"Invoke-Expression ('^& {' + (get-content -raw '%FilePath%') + '} %ARGS%')"
ECHO Exited PowerShell; Back in BATCH.
:# Wait 60 seconds before closing.
IF NOT "%noWait%" == "TRUE" (
TIMEOUT /T 60
)
if "%isUNC%" == "TRUE" (
IF "%noWait"=="True" (
TIMEOUT /T 5 >nul
)
POPD
) ELSE (
If NOT "%scriptDir%" == "%startDir" (
CD /D "%startDir%"
)
)
:# Exit Script
@endlocal & CALL ::EOF & EXIT /B
:# ############### End of the PS comment around the Batch section; Begin the PowerShell section. ############ : #>
Upvotes: 2
Reputation: 15299
The top-voted findstr
answer lacks these features which my solution has:
Read-Host
/pause
now works<# :
@set batch_args=%*
@powershell "iex ('$args = @(iex \"^& {`$args} $env:batch_args\");' + (cat -Raw '%~f0'))"
@exit /b %ERRORLEVEL%
#>
Write-Host Your PowerShell code goes here. First arg: $args[0] -fore Green
Read-Host Waiting for user to press Enter
Exit 42
If you do not need arguments, you can just do @powershell "iex (cat -Raw '%~f0')"
Explanation:
<# ... #>
is a comment block in PowerShell and thus skipped, but <# :
is interpreted as a null redirection in Batch and thus the comment is only run as batch code
exit /b %ERRORLEVEL%
makes it return the PowerShell exit code.ps1
ending, so instead of executing the current file directly with PowerShell, we call Invoke-Expression
/iex
instead to execute it
%~f0
in Batch is the name of the current code file$args
is normally an automatic PowerShell variable containing the command line arguments, but here we place a line on top of the loaded file which manually sets it@
in Batch prevents the command from being echoed back on the command line%*
in Batch refers to all arguments passed to the script.
& {$args} %*
snippet you see in some other answers creates a code block which just returns its arguments and executes it with the Batch arguments placed after it$args = (echo %*)
, then echo waits for user interaction if no args are passed :/@
ensures we always get an array, even if we have 0 argumentsThe ScriptBlock
-based answers have the problem that Write-Host
statements are immediately displayed while Write-Output
/echo
-based answers are only shown when the block completes, which is fatal for my use case (use Read-Host
to keep the cmd-window open in case of an error)
Upvotes: 0
Reputation: 307
A modified version of Red Riding Hood's answer. [ because the Stackoverflow edit queue is full :D ]
For completeness:
Code Snippet:
<# :
@PowerShell -ExecutionPolicy Bypass -NoLogo -NoProfile "& ([Scriptblock]::Create((Get-Content '%~df0' | Select-Object -Skip 4 | Out-String))) %*" & goto :eof
exit /b %errorlevel%
#>
Full Demo Script:
<# :
@PowerShell -ExecutionPolicy Bypass -NoLogo -NoProfile "& ([Scriptblock]::Create((Get-Content '%~df0' | Select-Object -Skip 4 | Out-String))) %*" & goto :eof
exit /b %errorlevel%
#>
Write-Output $PSVersionTable
Write-Output $args
$host.ui.RawUI.WindowTitle = "PowerShell Chimera"
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Start-Sleep -Seconds 5
Exit 0x539
Usage Example:
# demo.bat var1="1" var2='2' & echo %errorlevel%
# demo.bat "var1=1" 'var2=2' & echo %errorlevel%
Output:
Name Value
---- -----
PSVersion 5.1.19041.868
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.868
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
var1=1
var2=2
WINDOWS-PC\User
1337
Side note:
If you are not sure about the -NonInteractive
argument used in Red Riding Hood's original answer, i quoted a explanation below.
I think you are misunderstanding the use of the -NonInteractive
switch; you can still run powershell -noninteractive and get an interactive prompt. The NonInteractive
switch is intended for automated scripting scenarios, where you don't want powershell to send a prompt to the user and wait for a response. For example, in a non-interactive PowerShell window, if you run Get-Credential
without any parameters it will immediately fail instead of prompting for a username and password. Noninteractive will NOT act as a security mechanism.
A better method is to secure what you're trying to protect, not the tools a user might use to access it.
Source: jbsmith's answer to question "How to force PowerShell to not allow an interactive command window"
PS: This topic transformed into a PowerShell hacking contest :D
Upvotes: 0
Reputation: 2444
@powershell -noninteractive "& ([Scriptblock]::Create((gc '%~df0' | select -Skip 1 | Out-String))) %*" & goto :eof
Upvotes: 1
Reputation: 4938
my offering is as follows:
.\runner.bat
.\runner.bat -scope town
.\runner.bat -scope "whole universe"
@echo off & (For /F Delims^= %%a In ('CertUtil -HashFile %0 SHA1^|FindStr /VRC:"[^a-f 0-9]"') Do Set "PS1=%TEMP%\%%a.ps1" )
(if not exist %PS1% more +3 %0 > %PS1%) & (PowerShell.exe -ExecutionPolicy bypass -file %PS1% %* & goto :EOF)
@@@@@@[ PowerShell Starts Here ]@@@@@@
Param(
[String]$scope = "world"
)
write-host "hello $scope"
Upvotes: 0
Reputation: 11
bringing a few ideas together
<# :
@powershell -<%~f0&goto:eof
#>
Write-Output "Hello World"
Write-Output "Hello World again"
Upvotes: 1
Reputation: 5661
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
}
Upvotes: 1
Reputation: 646
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'" %*
Upvotes: 2
Reputation: 71
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
Upvotes: 5
Reputation: 57242
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.
Upvotes: 9
Reputation: 1423
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.
<# :# 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.)
Upvotes: 2
Reputation: 3795
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.
Upvotes: 2
Reputation: 46496
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.
Upvotes: 16
Reputation: 14272
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"
Upvotes: 5
Reputation: 14272
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
Upvotes: 26
Reputation: 3609
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
Upvotes: 3
Reputation: 40739
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%
Upvotes: 1