PowerShell's Get-ExecutionPolicy returns different values
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?
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
精彩评论