powershell return c# 中机器的每个驱动器为空 space

powershell return each drive empty space of machine in c#

我想使用 C#

清空 space 带有 powershell 的服务器的每个驱动器

这是运行良好的 powershell 脚本

Get-PSDrive |Format-Table

我想要的是获取此脚本的输出并在 UI

上显示

到目前为止我尝试了什么。

      string scriptToCheckDBServerMemorySpace = "Get-PSDrive |Format-Table";
      using (PowerShell PowerShellInstance = PowerShell.Create())
      {
                    PowerShellInstance.AddScript(scriptToCheckDBServerMemorySpace);

                    Collection<PSObject> PSObject = PowerShellInstance.Invoke();

                    foreach (PSObject PSOutputItem in PSObject)
                    {
                        if (PSOutputItem != null)
                        {

                            //TxtFirstStepResult.Text = PSOutputItem.BaseObject.ToString() + "\n";
                        }
                    }
                    if (PowerShellInstance.Streams.Error.Count > 0)
                    {
                        TxtFirstStepResult.Text = PowerShellInstance.Streams.Error.ToString() + "\n";
                    }
                    Console.ReadKey();
       }

问题是如何获取此 powershell 脚本的输出并将其显示在 windows 表单应用程序上。我不知道如何转换此 PS 对象并将其转换为可读格式。

请将我重定向到正确的方向。

您遇到的问题是您正在从脚本中取回格式化数据:

"Get-PSDrive |Format-Table"

数据并不像您在控制台中看到的那样 table - 您需要自己提取并显示它。更好的选择是获取 'raw' 对象并直接格式化它们。例如,这里有一些基本的控制台格式:

string scriptToCheckDBServerMemorySpace = "Get-PSDrive";
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript(scriptToCheckDBServerMemorySpace);

                Collection<PSObject> PSObject = PowerShellInstance.Invoke();

                foreach (PSObject PSOutputItem in PSObject)
                {
                    if (PSOutputItem != null)
                    {

                        Console.WriteLine($"Drive: {PSOutputItem.Members["Name"].Value}, Provider: {PSOutputItem.Members["Provider"].Value}");
                    }
                }
                if (PowerShellInstance.Streams.Error.Count > 0)
                {
                    //TxtFirstStepResult.Text = PowerShellInstance.Streams.Error.ToString() + "\n";
                }

                Console.ReadKey();
            }