c# - 如何从 C# 执行 PowerShell 命令 `open-device`?

标签 c# powershell powershell-3.0

我正在使用 open-device 127.0.0.1 连接远程设备。我如何从 C# 调用它?这段代码:

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

导致错误:

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)

但是,我可以使用 Invoke 运行 get-service 命令。

最佳答案

您需要首先使用 Import-Module 等效 cmdlet => 加载其模块,这是通过 InitialSessionStateImportPSModule() 方法完成的。

下面是我使用 DnsClient 模块的示例:

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();
        }
    }
}

关于c# - 如何从 C# 执行 PowerShell 命令 `open-device`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26370023/

相关文章:

c# - Task.WhenAny 是否将某些任务优先于其他任务?

.Net Core 中似乎缺少 MySqlDataAdapter

python - Django 管理员 - 登录

java - 使用powershell编译和运行java应用程序

c# - 在创建对象的线程上调用方法

c# - 极端线程安全集合

powershell - 如何在 PowerShell 二进制模块中捕获外部 DLL 的控制台输出?

powershell - 仅在嵌套循环中跳出内循环

iis - 如何从 PowerShell 指定应用程序池身份用户和密码

c# - NLog 拒绝抛出异常