Search code examples
c#powershellexecutionpolicy

Why isn't the new execution policy set from PowerShell visible from C#?


I have used the following code to successfully get the execution policy:

using (var powerShellInstance = PowerShell.Create())
{
    powerShellInstance.AddCommand("Get-ExecutionPolicy");
    Collection<PSObject> obj = powerShellInstance.Invoke();
}

I have used the following code to set the execution policy:

using (var powerShellInstance = PowerShell.Create())
{
    powerShellInstance.AddCommand("Set-ExecutionPolicy").AddArgument("ByPass");
    powerShellInstance.Invoke();
}

The problem is when I set the execution policy from PowerShell, the change is not visible in C#. If I set the execution policy from C# then the change is visible.

Consider the following scenario:

  • C# gets the execution policy Unrestricted.
  • PowerShell sets the execution policy to Bypass.
  • C# gets the execution policy Unrestricted.
  • C# sets the execution policy to Bypass.
  • C# gets the execution policy Bypass.

Solution

  • Scope!

    Set-ExecutionPolicy -Scope CurrentUser
    Set-ExecutionPolicy -Scope LocalMachine
    Set-ExecutionPolicy -Scope MachinePolicy
    Set-ExecutionPolicy -Scope Process
    Set-ExecutionPolicy -Scope UserPolicy
    

    I believe the default scope is Process (hence your issue)