Saturday, December 14, 2024
HomeWindowsBatch file programmingHow to run your own PowerShell scripts / cmdlets

How to run your own PowerShell scripts / cmdlets

By default, Microsoft has prevented the running of custom PowerShell scripts, a.k.a. cmdlets, by setting the PowerShell “ExecutionPolicy” to “Restricted”. This can be changed easily.

You can change the ExecutionPolicy for PowerShell scripts/cmdlets by running the PowerShell command Set-ExecutionPolicy.

To elaborate your options for this command, simply run the following in PowerShell:

Set-ExecutionPolicy -ExecutionPolicy -?

Personally, I prefer to set the ExecutionPolicy to “RemoteSigned”. This allows me to run my own scripts, but prevents unsigned scripts from others from running:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Test this as follows: Create a new PowerShell script on your Desktop. Right-click the Desktop, New > Text Document. Name it test.ps1

Right-click test.ps1 and select Edit. It should open up with PowerShell ISE (Integrated Scripting Environment). Type the following in the top pane:

Echo “Hello World!”

start-sleep 10

Save it with Ctrl + S, and close it.

Now open up powershell, change to your Desktop and try running the script:

cd “$env:userprofile\Desktop”

.\test.ps1

Then change your ExecutionPolicy to “RemoteSigned” and try again:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

.\test.ps1

Notice that the script/cmdlet is referenced using “.\”. You can also use the full path, but cannot run it by simply typing its name (very Unix like, eh?).

Also note the use of “$env:userprofile” to represent the path to your user profile. In the classic Windows Command Processor, this was represented with simply “%userprofile%”.

Lastly, please note that this will not work as indicated if you are not in the local Administrators group. It is, in fact, a best practice to avoid daily use of an account which is in the local Administrators group, so this may be the case for you. To work around it, simply launch powershell as an Administrator to set the execution policy. See here.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!