Sometimes it is more convenient to start the Powershell script by just clicking the filename in Windows Explorer.
Here are a couple of methods to start a Powershell script by clicking the filename or just typing the script name in a command shell.
Method 1: the Shortcut
Create a new shortcut on the Windows desktop or in some folder with the next properties:
- Create a shortcut on the desktop or in a folder with the next "Target" value:
- Associate PS1 files with this shortcut.
It will run the Powershell script but the console will be closed on completion. You may want to add a Start-Sleep or Read-Key command at the end of the script to observe the script output.
Method 2: using a Batch file
- Create a Batch file (c:\Scripts\psRun.bat) with the next content:
- Associate PS1 files with this Batch file.
Now the script runs and leaves the Console open, so the script output can be inspected.
Method 3: embed Powershell code in Batch file
Will give this output:
So how does it work? The Powerschell script is converted to Base64. The Windows utility CERTUTIL is used to encode the Powershell scrip to Base64 and all the script will be between the BEGIN/END certificate markers. This is used by CERTUTIL to recognize the code that needs to be translated back to Powershell code.
So the manual steps to create a script like this is:
1. Use the Batch file decoder code
2. Convert the Powershell script to Base64
C:\> certutil -encode HelloWorld.ps1 HelloWorld.ps1.b64
3. Append the HelloWorld.ps1.b64 output to the decoder code and save it as helloWorld.bat
To automate the whole process you may use the next script. Save as: makeBatchFromPowershell.bat:
Tying it all together:
You may rename the helloWorld.ps1-.bat to whatever BAT filename you want.