Try running your Set-ExecutionPolicy -Scope CurrentUser step within the runspace, like this.
First, with my ExecutionPolicy for this user to Restricted, and I see the following error when i run this code:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
//scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command("C:\\temp\\test.ps1");
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
}
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted");
Gives me
System.Management.Automation.PSSecurityException: 'File C:\temp\test.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.'
Next, I rerun it, uncommenting this line:
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
And, no errors! However, this will change the users ExecutionPolicy, which I think is bad behavior, so I'm going to instead wrap my function with this and set the Users ExecutionPolicy back the way I found it.
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("$ExecutionPolicy = Get-ExecutionPolicy -Scope CurrentUser");
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command("C:\\temp\\test.ps1");
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser $ExecutionPolicy -Force");
}
Now our function works and we don't tamper with the user's system settings.
usingstatement, but rather when you attempt to launch a script, we need to see the full body to see what you're doing.