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();
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.Errorcollection (.HadErrorsis a Boolean that indicates whether any errors occurred) - see this answer for details.Despite the
.AddScriptmethod'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.ps1file, us the.AddCommand()method, which is capable of reporting an exception your C# program can catch.A common problem with trying to invoke
.ps1files 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.
