PowerShell: Execution Policy

This is an example when Windows has an execution policy set as Restricted:

PS C:\Users\KimConnect> get-executionpolicy
Restricted

PS C:\Users\KimConnect> test.ps1

File C:\Users\KimConnect\test.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see
about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess

There are several ways to still execute PowerShell scripts on this system. Here are some of those methods:

# Quickest method to get around execution policy is to run this from an un-elevated PowerShell session. This will elevate to an Admin and change the policy

Start-Process powershell -ArgumentList 'Set-ExecutionPolicy -ExecutionPolicy Bypass -Force' -verb RunAs

# The better method, elevate as Admin and set execution policy on current script

#$scriptFile = "$(Get-Location)\"+$MyInvocation.MyCommand.Name
$scriptFile="C:\scripts\test.ps1"
Start-Process powershell -ArgumentList 'Powershell -ExecutionPolicy ByPass -File $scriptFile' -verb RunAs

# Alternatively, it's possible to relaunch script as an Admin

if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
# Relaunch as an elevated process:
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
exit
}

# The proper method
Set-ExecutionPolicy RemoteSigned
# Additional information:

# Discover whether host is 32-bit or 64-bit
Run CMD: echo %PROCESSOR_ARCHITECTURE%
Powershell Equivalent: [Environment]::Is64BitProcess

# Set Execution Policy on 32-bit or 64-bit systems

i386 (32 bit)
Open C:\Windows\SysWOW64\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned

amd64 (64 bit)
Open C:\Windows\system32\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned

Leave a Reply

Your email address will not be published. Required fields are marked *