繁体   English   中英

如何使用 C# 运行空间从本地计算机读取 Azure VM 中存在的远程 yaml 文件

[英]How to read remote yaml file present in Azure VM from local machine using C# Runspace

我想使用C# Runspace从我的本地机器读取远程azure vm中存在的远程yaml文件。

I'm able to run Powershell commands remotely using C# Runspace but I'm not getting how to read yaml file present in remote system like Azure VM using Runspace .

下面的代码用于从我的本地系统远程运行powershell命令。

               using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
                {
                    remoteRunspace.Open();
                    using (PowerShell powershell = PowerShell.Create())
                    {    
                        powershell.Runspace = remoteRunspace;
                        powershell.AddScript("Get-Service");    
                     }    
                }

通过我的测试,我可以读取服务器上的.yml文件。 下面是代码(.net framework 4.7.2)和截图。

vm 服务器中的44.yml文件。

在此处输入图像描述

通过 powershell 在 vm 服务器中读取文件。

在此处输入图像描述

通过我的代码读取文件。

在此处输入图像描述

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            var target = new Uri("http://***.***.***.**:5985/wsman");
            var secured = new SecureString();
            foreach (char letter in "yourpassword")
            {
                secured.AppendChar(letter);
            }
            secured.MakeReadOnly();

            var credential = new PSCredential("Administrator", secured);
            var connectionInfo = new WSManConnectionInfo(target, shell, credential);

            Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
            remoteRunspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;
                // your yml file in vm 
                powershell.AddScript("$textfile=\"C:\\website\\wps\\upload\\44.yml\";");
                //read file
                powershell.AddScript("Get-Content -Path $textfile");
                powershell.Invoke();

                Collection<PSObject> results = powershell.Invoke();

                // Display the results.
                foreach (PSObject result in results)
                {
                    Console.WriteLine(result.BaseObject);
                }
            }
            Console.Read();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM