Quick Tip: Windows PowerShell execution policy handling for x64 and x86 processes

Windows PowerShell’s execution policy is well known feature that helps prevent users from accidentally running malicious scripts. I hit an interesting situation recently where Get-ExecutionPolicy showed that I was allowed to run scripts, but in practice I still couldn’t execute scripts from a .NET application’s hosted runspace. What was the problem? The execution policy settings differed across x64 and x86 processes. Since this problem isn’t covered in the official documentation I figured it deserved a quick write-up.

Different execution policies for x86 and x64

On a 64-bit Windows computer open a Windows PowerShell prompt (the default x64 version), and then open the x86 version. Run Get-ExecutionPolicy -List in each session and view the results. Depending on how your machine was configured you may see different results for each session. Here is an example on one of my machines where the results differ:

Windows PowerShell x64 Session Policy
Windows PowerShell x86 Session Policy (same computer, different policy for x86)

Why is this happening?

This behavior can be explained when looking at the Windows registry. On a 64-bit Windows operating system, parts of the registry are stored separately for keys used by 32-bit applications and 64-bit applications (however there are also shared keys — read more here). This allows applications to have different stored settings that may apply specifically to one platform target.

Windows PowerShell uses platform specific (32 bit or 64 bit) registry keys instead of shared keys for some of the execution policy settings. You can verify this by running a tool like Sysinternals Process Monitor and then running execution policy commands.

An x64 PowerShell prompt querying execution policy settings against the x64 registry keys.
An x86 PowerShell prompt querying execution policy settings against the x86 registry keys. See the highlighted WOW6432Node path.

Tips for handling the execution policy

  • Use Group Policy to configure the execution policy settings. This will enforce a consistent experience across all machines.
  • If you can’t use group policy– remember to run your Set-ExecutionPolicy command in both x64 and x86 versions of PowerShell (if you use both).
  • If you host a runspace in a .NET application: remember that the AnyCPU build target will likely set your application as x86, which in turn would launch the x86 specific PowerShell runspace. If you need x64 PowerShell then be sure to set the platform target to x64.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s