5

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.
Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
s p
  • 789
  • 1
  • 6
  • 23

1 Answers1

1

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)

gvee
  • 16,732
  • 35
  • 50
  • This should be true. However, the help for `Set-ExecutionPolicy` says the default is different (`LocalMachine`), but I really doubt this one - it's a risk high enough to throw set-executionpolicy with machine by default. It's also possible that failing to set local machine policy the cmdlet changed scope to process. – Vesper Jun 02 '17 at 14:03
  • Great, I have changed scope to CurrentUser and then tested, working fine. – s p Jun 03 '17 at 16:53