-1

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

Bill Greer
  • 3,046
  • 9
  • 49
  • 80
  • 1
    I believe you need to elaborate a little more on the materials you're using to run this test. For instance, does your PS file contain any return statements ? If so, you should get back a Collection with whatever information you return. If you have Write-Output statements in your PS Script, they should also be part of the return. If you have Write-Errors/Warning/Progress (etc) statements, they will be part of the Streams (cf: https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.psdatastreams?view=powershellsdk-7.0.0) – Julien Oct 15 '22 at 20:00
  • 1
    You may be getting an exception. Add try/catch around the code. Do script run from PowerShell? Are you running inside VS? If you are a Admin then start VS by right click VS shortcut and select Run As Admin. – jdweng Oct 15 '22 at 20:33
  • There are many examples showing how to do this all over the web, on youtube, and right here on SO. Just use the SO search box above to find the. Your question really a duplicate of many others similar already asked and answered here on SO. – postanote Oct 15 '22 at 22:56

1 Answers1

1
  • 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.
mklement0
  • 382,024
  • 64
  • 607
  • 775