【问题标题】:How do I execute the PowerShell command `open-device` from C#?如何从 C# 执行 PowerShell 命令“open-device”?
【发布时间】:2014-12-09 18:58:45
【问题描述】:

我正在使用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:术语open-device 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,如果包含路径,请验证路径是否正确,然后重试。 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 命令。

【问题讨论】:

  • 离题,但我想知道:127.0.0.1(又名localhost)似乎不是很遥远......?

标签: c# powershell powershell-3.0


【解决方案1】:

您需要首先使用 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();
        }
    }
}

【讨论】:

  • 您好,感谢您的回复。 Open-device 是 tshell(Texus) 的 cmdslet,在 Powershell 上运行。但“System.Management.Automation”仅支持 Powershell CMDlets。
  • 我们要不要在 SO 中创建一个 TShell 标签?
猜你喜欢
  • 2016-04-04
  • 1970-01-01
  • 2012-08-03
  • 2017-06-08
  • 2016-05-18
  • 2010-10-06
  • 2013-12-09
相关资源
最近更新 更多