c# - 通过C#执行PowerShell函数脚本

标签 c# wpf powershell

我正在尝试学习如何将PowerShell集成到我正在开发的WPF / C#GUI中。我希望用户能够单击一个按钮,执行PowerShell脚本,然后返回信息并将其将输出写入richtextbox

这是PowerShell:

Function Get-MappedPrinters {

[Cmdletbinding()]
Param(
    [alias('dnsHostName')]
    [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [string]$ComputerName = $Env:COMPUTERNAME
)

$id = Get-WmiObject -Class win32_computersystem -ComputerName $ComputerName |
Select-Object -ExpandProperty Username |
ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }

$path = "Registry::\HKEY_USERS\$id\Printers\Connections\"

Invoke-Command -Computername $ComputerName -ScriptBlock {param($path)(Get-Childitem $path | Select PSChildName)} -ArgumentList $path | Select -Property * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName

}

这是C#
    private void SystemTypeButton_Click(object sender, RoutedEventArgs e)
    {
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript(File.ReadAllText(@"..\..\Scripts\systemtype.ps1"), true).AddParameter("ComputerName", ComputerNameTextBox.Text).AddCommand("Out-String");

            var results = ps.Invoke();
            MainRichTextBox.AppendText(results.ToString());
        }
    }

但是,它仅返回对象,而不返回其属性。 "System.Collections.ObjectModel.Collection1[System.Management.Automation.PSObject]"

有没有办法遍历对象?

最佳答案

您可以像其他数组一样使用foreach循环遍历对象。

另外,建议通过添加try catch块来处理异常,通过使用ps.Streams.Error获取错误缓冲区来处理powershell错误也可能会有所帮助。

using (PowerShell ps = PowerShell.Create())
{
     ps.AddScript(File.ReadAllText(@"..\..\Scripts\systemtype.ps1"), true).AddParameter("ComputerName", ComputerNameTextBox.Text).AddCommand("Out-String");
    Try
    {
         System.Collections.ObjectModel.Collection<PSObject> results = ps.Invoke();
    }
    catch (Exception e)
    {
         Console.WriteLine(e.Message);
    }

    foreach (var test in results)
          MainRichTextBox.AppendText(test.ToString());
}

相关问题:

Get Powershell errors from c#

How to read PowerShell exit code via c#

C# Powershell Pipeline foreach-object

关于c# - 通过C#执行PowerShell函数脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61855464/

相关文章:

sql-server - Enter-PSSession 后 Invoke-SqlCmd 出现 'NT AUTHORITY\ANONYMOUS LOGON' 错误?

c# - 在.NET Core应用程序中使用NEST在ElasticSearch中的正确索引路径内进行批量收集

c# - 如何将第一项设置为选中

c# - 如何将一个对象的成员绑定(bind)到数据网格

powershell - 如何使用 Powershell 管道避免大对象?

powershell - 从 Powershell 调用带有非常长的可变参数列表的程序?

c# - 图像的分离和分析

c# - 如何使 Entity Framework 仅在查询字段不为空时过滤数据?

c# - MS-Access - 您尝试执行的操作不包含指定表达式 'Quantity' 作为聚合函数的一部分

c# - ListBox 使用 caliburn.micro 自动调整大小不正确