user1752840
user1752840

Reputation: 31

How do I execute the PowerShell command `open-device` from C#?

I am using open-device 127.0.0.1 to connect a remote device. How do I invoke this from C#? This code:

PowerShell powerShell = PowerShell.Create(); 
PSCommand connect = new PSCommand();
connect.AddCommand("open-device");
powerShell.Commands = connect;
PSOutput = powerShell.Invoke()

results in the error:

System.Management.Automation.CommandNotFoundException: The term open-device is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. at

 System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) at
 System.Management.Automation.Runspaces.Pipeline.Invoke() at
 System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspa‌​ce rs, Boolean performSyncInvoke)

However, I am able to run the get-service command using Invoke.

Upvotes: 2

Views: 4456

Answers (1)

vasja
vasja

Reputation: 4792

You need to load its module first with Import-Module cmdlet equivalent => that is done via ImportPSModule() method of InitialSessionState .

Below my example with DnsClient module:

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;

namespace PowershellTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();
            String[] modules = { "DnsClient" };
            initial.ImportPSModule(modules);
            Runspace runspace = RunspaceFactory.CreateRunspace(initial);
            runspace.Open();
            RunspaceInvoke invoker = new RunspaceInvoke(runspace);

            Collection<PSObject> results = invoker.Invoke("Resolve-DnsName 'localhost'");
            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                foreach (PSMemberInfo m in obj.Members)
                {
                    stringBuilder.AppendLine(m.Name + ":");
                    stringBuilder.AppendLine(m.Value.ToString());
                }
            }

            Console.WriteLine(stringBuilder.ToString());
            Console.ReadKey();
        }
    }
}

Upvotes: 0

Related Questions