Posted On April 13, 2019

PowerShell: Execution Policy

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

Basic HTML and HTML5: Nest an Anchor Element within a Paragraph

<h2>CatPhotoApp</h2><main><a href="http://freecatphotoapp.com" target="_blank">cat photos</a><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."><p>Kitty ipsum dolor…

RDP Gateway with MFA

Step 1: Install RDS Gateway   Prerequisites: 1. Enable Power Shell Remoting  2. SSL Certs…

How To Add or Remove a Path in Windows Environmental Paths

There are 2 functions to Add and Remove, at your convenience: # addEnvironmentalPath.ps1 $pathToAdd='C:\Scripts' $pathToRemove='C:\Scripts'…