Home > OS >  How do I run a PowerShell Script from C# with System.Management.Automation
How do I run a PowerShell Script from C# with System.Management.Automation

Time:10-16

I am trying to run the following code from the Microsoft link below. I do not get any errors but the Powershell script is never executed.

PowerShell ps = PowerShell.Create();
ps.AddScript("D:\PSScripts\MyScript.ps1").Invoke();

https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/windows-powershell-host-quickstart?view=powershell-7.2

CodePudding user response:

  • When you use the .AddScript() PowerShell SDK method, any errors that occur during execution of the PowerShell code do not surface as exceptions in your C# program; instead, you must examine the .Streams.Error collection (.HadErrors is a Boolean that indicates whether any errors occurred) - see this answer for details.

  • Despite the .AddScript method's name, it is not designed to invoke script files (.ps1); instead, its purpose is to invoke arbitrary PowerShell code passed as a string. In order to invoke a .ps1 file, us the .AddCommand() method, which is capable of reporting an exception your C# program can catch.

  • A common problem with trying to invoke .ps1 files on Windows is that the effective script execution policy prevents it; notably, on desktop editions of Windows script-file execution is disabled by default (Restricted), whereas in recent server editions it defaults to allowing execution except for script files downloaded from the web (RemoteSigned).

    • This answer shows how to bypass the effective execution policy via the SDK on a per-process basis, but note that if the execution policy on a given machine / for a given user is set via GPOs (Group Policy Objects), bypassing is not possible.
  • Related