Running a PowerShell Script that is a Batch File

Just a bit of a curiosity this one...

This post is not about invoking a PowerShell script from a batch file, but about running a batch file that contains the PowerShell script! It is possible, but this might be cheating...

Recipe

1) Create your PowerShell script as per normal
2) REM out every line in the PowerShell script - "REM "
3) Save the script as a .BAT file
4) At some point in the script (top’s as good a place as anywhere), place this DOS command shell line -

powershell.exe [System.Array]$Outfile = @(); Foreach( $line in (get-content TEST.bat) ){ If($Line.StartsWith('REM ')){ $Outfile += $Line.replace('REM ','') }else{ $Outfile += ('# ' + $Line) } }; Out-File -filepath TEST.ps1 -InputObject $OutFile -Encoding Default; .\TEST.ps1

- replacing TEST with the name of your file.
5) Then double-click your .BAT file - that is your PowerShell script disguised behind some REM Statements - to run!

What does it do?

Essentially, from the one line*, it reads the BAT file, and outputs it as a PS1 file, removing "REM " and adding # to any other line. Then it runs the PS1 file it’s just created.

*has to all be on one line, and can’t use double-quotation marks or the pipe symbol

Taking it Further

Okay, so now there are two files. I could have overwritten the original BAT; better, just need the PowerShell script to delete itself before it finishes.

Why?

Well, it solves the questions:
Q1 “But why do I need two files?” (If using a .BAT to invoke a .PS1)
Q2 “Why can’t I just double-click the file?” (If they’ve been instructed to right-click the .PS1 and click “Run with PowerShell”)

Comments