[英]How do I execute the PowerShell command `open-device` from C#?
我正在使用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(Runspace rs, Boolean performSyncInvoke)
但是,我可以使用Invoke
运行get-service
命令。
您需要与第一加载其模块Import-Module
cmdlet的当量=>经由完成ImportPSModule()
的方法InitialSessionState
。
下面是我的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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.