Home > Uncategorized > Batch file bootstrap PowerShell script for easy double click running

Batch file bootstrap PowerShell script for easy double click running

February 16th, 2012 Leave a comment Go to comments

The scenario is you have a PowerShell script that takes no paramaters and prompts the user for all the information it needs. How do you make it extra simple for people to check it out of source control and run it?

You have 1 .bat or .cmd file in the root of the folder. Create a subfolder like internal and put all your ps1 files in there. Here is what I put together so you could just double click the .bat/.cmd file and have your PowerShell script execute without worry.

@echo off
setlocal
REM Check to see if Powershell is in path
for %%X in (powershell.exe) do (set FOUND=%%~$PATH:X)
if not defined FOUND (
	echo Please install PowerShell v2 or newer.
	pause
	exit /b 1
)

REM Check to see if we have powershell v2 or later
PowerShell.exe -command "& { if ($host.Version.Major -lt 2) { exit 1 } }"
if %ERRORLEVEL% EQU 1 (
	echo Please upgrade to PowerShell v2 or later.
	pause
	exit /b 1
)

REM Set scriptDir to directory the batch file is located
set scriptDir=%~dp0
echo Running powershell.exe %scriptDir%internal\MyScript.ps1
REM Note the RemoteSigned in case the system is defaulted to restricted
powershell.exe -ExecutionPolicy RemoteSigned -command "& { "%scriptDir%internal\MyScript.ps1"; exit $LastExitCode }"
if "%ERRORLEVEL%" NEQ "0" (
	echo There may have been a problem with MyScript.  Please read the above text carefully before exiting.
)
pause
endlocal

After replacing MyScript with the name of your script, stick the contents in MyScript.cmd in your main directory. Make sure you have your powershell script in a subdirectory called internal. When the user double clicks on the file we check if PowerShell is in the path and that it is v2 or greater. We abort if either of those conditions are false. Finally we execute the PowerShell script with paramaters to ensure it runs on a new system without having the execution policy set yet. If you exit your powershell script with a non-zero the batch file will remind the user to read carefully before the window closes.

Categories: Uncategorized Tags: ,
  1. No comments yet.
  1. No trackbacks yet.