Reputation: 95
I've the below powershell script file
C:\user\deskptop\script1.ps1
The contents of the script is just the below:
get-process
i'm trying to create a C# console app to get the output of this script on console. When i execute the script outside C# it runs fine but when i execute it inside C# it doesn't produce anything. i'm trying use addscript and invoke.
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace InvokePowerShellScriptFrmCsharp1
{
class Program
{
static void Main(string[] args)
{
string script = @"C:\\Users\\Desktop\\script1.ps1";
PowerShell shell = PowerShell.Create();
shell.AddScript(script);
//shell.AddCommand("get-process");
shell.Invoke();
//shell.AddScript(script).Invoke();
Collection<PSObject> pSObjects = shell.Invoke();
foreach (PSObject p in pSObjects)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
}
When i execute the above i get the console with 'Press any key to continue' but no output before that.
but if i just try the below i get the result
shell.addcommand("get-process");
I want to get this working with addscript coz in the future if there is more than one command in the powershell script then i need to be able to execute the script from C# for desired results.
i've tried many links to try research but don't seem to be getting it to work.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
https://www.reddit.com/r/csharp/comments/692mb1/running_powershell_scripts_in_c/
Could someone please let me know where i could be going wrong.
Upvotes: 3
Views: 7789
Reputation: 8442
Try loading the script contents first, then passing that to the AddScript
method:
string script = File.ReadAllText(@"C:\Scripts\script1.ps1");
Upvotes: 6