Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell's Get-ExecutionPolicy returns different values

Tags:

c#

powershell

Depending on the method I used to get the execution policy setting for PowerShell, I get two different values.

If I run Get-ExecutionPolicy in a PowerShell prompt, I get 'Unrestricted'.

If I use the following code, I get 'Restricted'.

using (var runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();

    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Get-ExecutionPolicy");

    foreach (var result in pipeline.Invoke())
    {
        var restriction = ((ExecutionPolicy)result.BaseObject);
        break;
    }
}

Again, I get 'Restricted' with the following code:

using (var invoker = new RunspaceInvoke())
{
    foreach (var result in invoker.Invoke("Get-ExecutionPolicy"))
    {
        var restriction = ((ExecutionPolicy)result.BaseObject);
        break;
    }
}

I also checked in the registry here: HKEY_Local_Machine\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.Powershell\ExecutionPolicy and there it says Unrestricted.

Why do I get a different result? Is my code incorrect perhaps?

like image 903
joerage Avatar asked Nov 29 '25 08:11

joerage


1 Answers

Are you implementing a custom host? If so, the default execution policy would be restricted and would need to be set for that host (under ShellIds).

Either way, you should be able to execute this command first in your code to override the setting:

Set-ExecutionPolicy RemoteSigned -Scope process
like image 168
Keith Hill Avatar answered Nov 30 '25 21:11

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!