2

I need to configure ExecutionPolicy as 'RemoteSigned' at initial session state or somehow before execution of script. I don't want to execute script to set policy. This would alter the policy at client machine which i don't want.

In Powershell 5.0 reference assemblies one can do easily,

var iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned

but how can I achieve the same while remaining with Powershell 4.0 as referenced assemblies.

C# code to execute script

var iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned; --> this is OK for Powershell ReferenceAssemblies 5.0 but not 4.0

iss.ImportPSModule(new[] { typeof(Parameter).Assembly.Location });
using (var powerShell = PowerShell.Create(iss))
{
     var psScript = _inlineScript ?? File.ReadAllText(_path);
     powerShell.AddScript(psScript);
}
Usman
  • 2,742
  • 4
  • 44
  • 82

1 Answers1

1

Do you mean when you launch PowerShell? if so can you do this:

powershell -ExecutionPolicy RemoteSigned ... rest of parameters here

I know we have several scripts that start out this way.

No Refunds No Returns
  • 8,092
  • 4
  • 32
  • 43
  • No no. I don't want to run Windows Powershell at all. I want to set it from C# code before executing script using PowerShell api.. See the edit above – Usman Aug 28 '18 at 17:12
  • 1
    You may have answered your own question if you are asking how to call an API that isn't available to you. You can't. I must not understand your question. This answer does not change the user profile setting, it's only effective for this invocation of PowerShell. – No Refunds No Returns Aug 28 '18 at 17:15
  • Can I ask one question what happens when I run the following code. using (var powerShell = PowerShell.Create(iss)) { string script = "Set-ExecutionPolicy Unrestricted"; powerShell.AddScript(script); var putput = powerShell.Invoke(); } – Usman Aug 30 '18 at 10:26