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

PowerShell: Backup Microsoft Dynamics CRM Database

# backupCrmOrgDatabase.ps1 # This script is to be invoked in the context of the Administrator…

PowerShell: Get Failed Scheduled Tasks on a Windows Machine

The following function will query the local Windows Tasks Scheduler for custom schedules and output…

PowerShell: Auto Login to WordPress and Update Gold Prices WooCommerce Plugin

# API URI - these are examples, only $goldPriceApi='https://dragoncoin.com/XAU/USD' $silverPriceApi='https://dragoncoin.com/XAG/USD' $platinumApi='https://dragoncoin.com/XPT/USD' $palladiumApi='https://dragoncoin.com/XPD/USD' # Wordpress WooCommerce…