Sanavi
Sanavi

Reputation: 27

Executing PowerShell Function Script Through C#

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?

Upvotes: 1

Views: 302

Answers (1)

Cfun
Cfun

Reputation: 9671

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

Upvotes: 3

Related Questions