Search code examples
c#powershellpsobject

Running powershell with C#


I am trying to run the following powershell command inside of C#

Powershell:

"Get-ADDomainController -Filter * | Select-Object Name,OperatingSystem,OperatingSystemServicePack,Site | Format-List"

Here is my C# Code:

using (PowerShell inst = PowerShell.Create())
        {
            inst.AddCommand("Import-Module").AddParameter("Name", "ActiveDirectory");
            inst.AddScript(command);
            inst.Commands.AddCommand("Out-String");
            foreach (PSObject result in inst.Invoke())
            {
                Console.WriteLine("'{0}'", result);
            }

            Console.ReadLine();
        }

This works fine and prints out the results, but what I want to be able to do is iterate through the information

So for example the results printed look like this

Name: xxx OperatingSystem: Windows Server 2008 OperatingSystemServicePack: Service Pack 2 Site: xxx

I want to be able to do a foreach and add the name, operatingsystem, site to a list.

Hope that makes sense


Solution

  • Ok So here is the fix I wanted, thought I would share in case it helps anyone else

    the first thing I done was got rid of the Format-List command in powershell then I could iterate through the results with the following C# code and put it inside a list

    List<DomainControllerLists> dcList = new List<DomainControllerLists>();
            using (PowerShell inst = PowerShell.Create())
            {
                inst.AddCommand("Import-Module").AddParameter("Name", "ActiveDirectory");
                inst.AddScript(command);
                Collection<PSObject> results = inst.Invoke();
                foreach (PSObject obj in results)
                {
                    dcList.Add(new DomainControllerLists() { Name = obj.Members["Name"].Value.ToString(), OperatingSystem = obj.Members["OperatingSystem"].Value.ToString(), OperatingSystemServicePack = obj.Members["OperatingSystemServicePack"].Value.ToString(), Site = obj.Members["Site"].Value.ToString() });
                }
            }
            return dcList;
    

    this now returns a list with the information I need You could pretty this up by converting the foreach loop into a LINQ statement