I'm trying to run a basic powershell script in a c# application, but I can't seem to get it to run. I've tried this code with and without the added execution policy code in the pipeline creation and have gotten the same results.
static void Main(string[] args)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");
pipeline.Commands.Add(@"C:\Users\Bob\Desktop\testScript.ps1");
// Execute PowerShell script
var results = pipeline.Invoke();
}
The error I receive is this:
System.Management.Automation.PSSecurityException: 'File C:\Users\Bob\Desktop\testScript.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.'
When I run "get-executionpolicy -list", my execution policy seems to be fine.
Normally, the persistently configured script execution policy applies to PowerShell SDK-based projects such as yours, too.
While your
Get-ExecutionPolicy
-List
output implies thatRemoteSigned
is the effective policy (as reported when you omit-List
), the color of your screenshots suggest that you were asking for Windows PowerShell's policy, which is separate from the execution policy for the cross-platform, install-on demand PowerShell (Core) v6+ edition.Therefore, your inability to execute a local script - which
RemoteSigned
should allow - can have one of two causes:If you project is based on the SDK for PowerShell (Core) v6+ (via the
Microsoft.PowerShell.SDK
NuGet package), you'd have to consult - and possibly modify - its effective execution policy (runpwsh -c Get-ExecutionPolicy
to see the policy in effect)As Mathias points out in a comment, another possible reason is that your local script may have been downloaded from the web, via a web browser, in which case it is considered a remote file for the purpose of the execution policy. Passing its file path to
Unblock-File
as a one-time action should fix the problem.Taking a step back:
If you trust the local script to invoke, you can bypass the execution policy for your application only, by configuring your PowerShell SDK session accordingly - see this answer.