I'd like to wrap a PowerShell script into a batch file to finally make it executable for anybody and in a single distributed file. My idea was to begin a file with CMD commands that read the file itself, skipping the first couple lines and piping the rest to powershell, then let the batch file end. In Bash that would be an easy task with short readable commands, but you can see from the numerous tricks that Windows has big trouble with this already. That's how it looks like:
@echo off
(for /f "skip=4 delims=" %%a in ('type %0') do @echo.%%a) |powershell -noprofile -noninteractive -
goto :EOF
---------- BEGIN POWERSHELL ----------
write-host "Hello PowerShell!"
if ($true)
{
write-host "TRUE"
}
write-host "Good bye."
The problem is, the PowerShell script doesn't execute completely, it stops after the first written line. I could make it work some more, depending on the script itself, but couldn't find any pattern here.
If you pipe the result from line 2 to a file or to a cat
process (if you have unix tools installed, Windows can't even do that on its own), you can see the complete PowerShell part of the file, so it's not cut off or something. PowerShell just doesn't want to execute the script here.
Copy the file, remove the first 4 lines and rename it to *.ps1, then call this:
powershell -ExecutionPolicy unrestricted -File FILENAME.ps1
And it'll execute completely. So it's not the PowerShell script content either. What is it that lets powershell end prematurely in this case?