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

Viewed 491

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.
1 Answers
Related