batch-file Run Powershell with Temporary Files


Example

This has been mentioned in other hybrid topics again and again. The old-school, but easy method to run Powershell is by:

  • echoing the Powershell script into a temporary script
  • Execute the temporary script
  • Optionally remove the temporary script

This is a sample script.

@echo off
echo powershell-command>Temp.ps1
echo another line>>Temp.ps1
    rem echo the script into a temporary file

powershell -File Temp.ps1
    rem execute the temporary script

del Temp.ps1
    rem Optionally remove the temporary script

The method above requires tons of echo statement if a long script is required, here is a better method suggest by @Aacini

@echo off
setlocal

    rem Get the number of the "<resource>" line
for /F "delims=:" %%a in ('findstr /N "<resource>" "%~F0"') do set "start=%%a"

    rem Skip such number of lines and show the rest of this file
(for /F "usebackq skip=%start% delims=" %%a in ("%~F0") do echo %%a) > Temp.ps1

powershell -File Temp.ps1
del /f /s /q Temp.ps1

goto :EOF

<resource>
PS
Powershell script