我正在尝试编写一个C#核心程序,以在远程linux系统上运行powershell脚本。在.net core上运行是此项目的要求。我正试图宽松地遵循在CodeProject上找到的指南。
这是我的代码:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SSHConnectionInfo connectionInfo = new SSHConnectionInfo(userName: "user", computerName: "server", keyFilePath: "id_rsa");
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open(); // The program errors out here
runspace.Close();
}
}
}
}
我的“ id_rsa”文件位于与程序相同的文件夹中。我已验证Windows的openssh,powershell核心6.0.2和.net核心2 SDK已安装并正常工作。我正在使用Microsoft Powershell Core repository中的以下nuget软件包:Microsoft.PowerShell.SDK(6.0.2)和Sytem.Managment.Automation(6.0.2)
这是我收到的错误:
Unhandled Exception: System.Management.Automation.Remoting.PSRemotingDataStructureException: An error has occurred which PowerShell cannot handle. A remote session might have ended. ---> System.ArgumentException: The path is not of a legal form.
Parameter name: path
at System.IO.Path.GetDirectoryName(String path)
at System.Management.Automation.Runspaces.SSHConnectionInfo.StartSSHProcess(StreamWriter& stdInWriterVar, StreamReader& stdOutReaderVar, StreamReader& stdErrReaderVar)
at System.Management.Automation.Remoting.Client.SSHClientSessionTransportManager.CreateAsync()
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.SendNegotiationAsync(RemoteSessionState sessionState)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.HandleStateChanged(Object sender, RemoteSessionStateEventArgs arg)
at System.Management.Automation.ExtensionMethods.SafeInvoke[T](EventHandler`1 eventHandler, Object sender, T eventArgs)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.RaiseStateMachineEvents()
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.ProcessEvents()
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.Runspaces.Internal.RunspacePoolInternal.EndOpen(IAsyncResult asyncResult)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.Open()
at System.Management.Automation.RemoteRunspace.Open()
at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 18
Press any key to continue . . .
这时我不确定我缺少什么。
答案 0 :(得分:0)
我最终在github上打开了一个issue来解决此错误。当前要解决此问题,您将需要在程序中添加以下代码,直到在以后的Powershell内核版本(> 6.0.4或> 6.1.0-rc.1)中解决此issue为止。 Here is the specific post regarding the issue.
if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace == null)
{
var defaultRunspace = RunspaceFactory.CreateRunspace();
defaultRunspace.Open();
System.Management.Automation.Runspaces.Runspace.DefaultRunspace = defaultRunspace;
}