How to enable execution of PowerShell scripts

PowerShell Execution Policy

The PowerShell Execution Policy determines whether PowerShell scripts are allowed to run. By default, the Execution Policy is set to Restricted. If you try to run scripts under the Restricted policy, you will get error messages.

In this tutorial, you will learn about the execution policies, how to enable execution of PowerShell scripts on machine.

What is Execution Policy


PowerShell's execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps to prevent the execution of malicious scripts.

The execution policy isn't a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating those unintentionally.

Execute PowerShell Script


I have created a "sample.ps1" powershell script having Get-Date command and placed it in my C drive. Lets try to execute this.
As you can see, script file cannot be loaded because running scripts is disabled on this system.

Run Get-ExecutionPolicy to see what execution policy is in place.
For me, it's restricted that's why I got error when tried to execute "sample.ps1" script. 

To display the execution policies for each scope in the order of precedence, use Get-ExecutionPolicy -List

Change the Execution Policy


To change execution policy we have Set-ExecutionPolicy command. use Get-Help command to know more about this.

If you pass -example parameter along it, you will get multiple example of how you can use set-ExecutionPolicy as per your need.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned


Default scope is LocalMachine. As you can see in snapshot, execution policy is updated but setting is overridden by policy from more specific scope. to verify result, run Get-ExecutionPolicy -list

It means we need to change execution policy at MachinePolicy scope level. Let make the changes

We got a error message means we cannot make change at MachinePolicy level using Set-ExecutionPolicy. To make the required changes we  need to go in the registry and edit the following key HKLM:\Software\Policies\Microsoft\Windows\PowerShell and change the ExecutionPolicy to RemoteSigned 

OR 

run below command.

Verify the result of above command.

Now Let's execute our "sample.ps1" script.

YouTube video link:


Comments

Popular Posts

How to Import and Export Delimited Files, like CSV, in PowerShell

PowerShell Arithmetic Operators

How to generate a GUID in PowerShell