PowerShell by Example: Execution Policies
Understanding and managing script execution security with this code example demonstrating policy scopes, setting policies, and unblocking downloaded files.
Code
# Get current execution policy
Get-ExecutionPolicy -List
# Set policy to RemoteSigned for the current user (safest default)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
# Bypass policy for a single script execution (Process scope)
powershell.exe -ExecutionPolicy Bypass -File ".\setup.ps1"
# Unblock a file downloaded from the internet
Unblock-File -Path "C:\Downloads\script.ps1"
# Check effective policy
$policy = Get-ExecutionPolicy
Write-Host "Effective Policy: $policy"Explanation
PowerShell Execution Policies are a safety feature, not a security boundary, designed to prevent the accidental execution of malicious scripts. They control the conditions under which PowerShell loads configuration files and runs scripts. The default policy on Windows client computers is often Restricted, which prevents all scripts from running. Common policies include RemoteSigned (requires digital signatures for downloaded scripts), AllSigned (requires signatures for all scripts), and Bypass (nothing is blocked). Understanding these policies is crucial for configuring a secure yet functional automation environment.
Execution policies can be applied at different scopes, with a specific order of precedence: MachinePolicy (GPO), UserPolicy (GPO), Process (current session), CurrentUser, and LocalMachine. This hierarchy allows administrators to enforce rules via Group Policy while enabling developers to override settings locally for testing, provided GPO doesn't forbid it. The Process scope is particularly useful for temporarily bypassing restrictions for a single session without permanently altering system-wide security settings.
When scripts are downloaded from the internet, Windows attaches a "Zone.Identifier" alternate data stream, marking them as potentially unsafe. Even with RemoteSigned, these files must be explicitly trusted using the Unblock-File cmdlet before they can run. This mechanism ensures that users make a conscious decision to execute code from external sources. Best practice dictates using the most restrictive policy that still allows your work to proceed, typically RemoteSigned for developers and AllSigned for enterprise production environments.
- Use
Get-ExecutionPolicy -Listto view all active scopes - Set
RemoteSignedfor a balance of security and usability - Use
Unblock-Fileto trust downloaded scripts - Understand that execution policies are not a replacement for antivirus
Code Breakdown
Get-ExecutionPolicy -List displays policies for all precedence scopes.Set-ExecutionPolicy changes the policy for the specified scope.-ExecutionPolicy Bypass runs a script without policy restrictions.Unblock-File removes the "Zone.Identifier" stream from downloaded files.
