简体   繁体   中英

Powershell addscript and invoke from C# not displaying result on command line

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.

尝试先加载脚本内容,然后将其传递给AddScript方法:

string script = File.ReadAllText(@"C:\Scripts\script1.ps1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM