1

I'm trying to learn how to incorporate PowerShell into a WPF/C# GUI I'm working on. I'd like the user to be able to click a button, have the PowerShell script execute, and then returns the information and have it write the output to a richtextbox.

Here is the 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

}

And here is the 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());
        }
    }

However, it is only returning the object and not its properties. "System.Collections.ObjectModel.Collection1[System.Management.Automation.PSObject]".

Is there a way to iterate through the object?

1 Answer 1

3

You can iterate thru the object using foreach loop like any other array.

Also it is advisable to handle exceptions by adding a try catch block, and handling powershell errors by getting the error buffer using ps.Streams.Error can be helpful also.

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());
}

Related questions:

Get Powershell errors from c#

How to read PowerShell exit code via c#

C# Powershell Pipeline foreach-object

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.