Skip to content

Instantly share code, notes, and snippets.

@neuralpain
Last active August 8, 2024 02:57
Show Gist options
  • Save neuralpain/4ca8a6c9aca4f0a1af2440f474e92d05 to your computer and use it in GitHub Desktop.
Save neuralpain/4ca8a6c9aca4f0a1af2440f474e92d05 to your computer and use it in GitHub Desktop.
Run a PowerShell code block once in a batch script at any given time and return to Batch when done.
<# :# 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 1
:: extracted from https://stackoverflow.com/a/61821651
::------------------------------------ SIMPLIFIED -----------------------------------::
<# :# DO NOT REMOVE THIS COMMENT
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set ARGS=%*
if defined ARGS set ARGS=%ARGS:"=\"%
if defined ARGS set ARGS=%ARGS:'=''%
:: TODO, optional Batch code to run before PowerShell is executed...
:: ...
PowerShell -c ^"$CMD_NAME='%~n0';Invoke-Expression ('^& {' + (get-content -raw '%~f0') + '} %ARGS%')"
:: $CMD_NAME contains the name of the batch file (without
:: the extension), which is used to identify the script and
:: is passed to PowerShell
:: ---
:: Optionally catch PowerShell exit codes with %ERRORLEVEL%...
:: TODO, supplementary batch code to run after PowerShell has exited...
:: ...
exit /b
#>
# TODO, PowerShell code to execute...
# ...
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment