代码之家  ›  专栏  ›  技术社区  ›  Dan The Man

新的PSSession使Ubuntu无法使用.NET核心包运行到Windows

  •  2
  • Dan The Man  · 技术社区  · 6 年前

    我使用的是Ubuntu 16.04,我用.NET Core编写了一个项目,并安装了以下nuget包:

    System.Management.Automation 6.02
    Microsoft.WSMan.Management 6.02
    Microsoft.PowerShell.SDK 6.02
    Microsoft.PowerShell.Commands.Management 6.02
    Microsoft.Management.Infrastructure 1.00
    

    使用以下代码:

    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    
    pipeline.Commands.AddScript("$secpasswd = ConvertTo-SecureString \"MyPassowrd\" -AsPlainText -Force");
    pipeline.Commands.AddScript("$mycreds = New-Object System.Management.Automation.PSCredential (\"admin\", $secpasswd)");
    pipeline.Commands.AddScript("$session = New-PSSession -ComputerName 10.81.4.4 -port 5985 -Credential $mycreds -Authentication Negotiate");
    pipeline.Commands.AddScript("Invoke-Command -Session $session -ScriptBlock {get-service}");
    var resPipe = pipeline.Invoke();
    

    我得到这个错误:

    Exception :The method or operation is not implemented. The method or operation is not implemented. at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)\n at System.Management.Automation.Runspaces.Pipeline.Invoke()
    

    问题是,如果我在我的Ubuntu中使用powershell 6.0,并尝试使用上面的命令获取会话,它会工作,但是当使用.NET Core时,我会得到一个错误,

    有人知道为什么吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Dan The Man    6 年前

    最后,我使用以下代码运行我的命令集:

    public static string RunCommand(string cmd)
    {
    
            var base64EncodedString = Convert.ToBase64String(ASCIIEncoding.Unicode.GetBytes(cmd));
    
            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "pwsh",
                    Arguments = $"-encodedcommand \"{base64EncodedString}\"",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return result;
    }
    

    其中,cmd param是我的所有命令与;分隔符的连接。

    对于windows到windows远程处理,文件名应为:

    FileName = @"C:\Program Files\PowerShell\6.0.4\pwsh.exe",