I try to run powershell
script from c#.
First i set the ExecutionPolicy
to Unrestricted
and the script is running now from PowerShell ISE
.
Now this is c# my code:
class Program { private static PowerShell ps; static void Main(string[] args) { ps = PowerShell.Create(); string ps1File = Path.Combine(Environment.CurrentDirectory, "script.ps1"); ExecuteScript(ps1File); Console.ReadLine(); } static void ExecuteScript(string script) { try { ps.AddScript(script); Collection<PSObject> results = ps.Invoke(); Console.WriteLine("Output:"); foreach (var psObject in results) { Console.WriteLine(psObject); } Console.WriteLine("Non-terminating errors:"); foreach (ErrorRecord err in ps.Streams.Error) { Console.WriteLine(err.ToString()); } } catch (RuntimeException ex) { Console.WriteLine("Terminating error:"); Console.WriteLine(ex.Message); } } }
And the output is:
ps1 cannot be loaded because running scripts is disabled on this system. For more informationm see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
ps1 cannot be loaded because running scripts is disabled on this system" occurs when the execution policy does not allow running the specific script on Windows. Use the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command to solve the error.
This could be due to the current user having an undefined ExecutionPolicy
.
You could try the following:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With