gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:48 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com