Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell Calculated Properties from C#

So I want to execute PowerShell Calculated Properties (I hope that's the correct name) from C#.

My CmdLet in the PS (Exchange) Console looks like this:

Get-Something -ResultSize unlimited |Select-Object DisplayName,@{name="RenamedColumn;expression={$_.Name}},ToBeExpanded -Expand ToBeExpanded |Select-Object DisplayNameRenamedColumn,ToBeExpandedGuid

This works just fine, the problem occures when I try to execute it from C#.

My Code looks like this:

List<string> parameters = new List<string>()
            {
                "DisplayName","@{{name=\"RenamedColumn\";expression={{$_.Name }} }}","ToBeExpanded"
            };
List<string> parameters2 = new List<string>()
            {
                "DisplayName","RenamedColumn","ToBeExpanded","ToBeExpandedGuid"
            };
    powershell.AddCommand("Get-Something");
    powershell.AddParameter("ResultSize","unlimited");
    powershell.AddCommand("Select-Object");
    powershell.AddParameter("Property",parameters);
    powershell.AddParameter("ExpandProperty","ToBeExpanded");
    powershell.AddCommand("Select-Object");
    powershell.AddParameters("Property",parameters2);

    result = powershell.Invoke();

My result then contains the empty ToBeExpandedGuid (null). So I tried the command without the second select and it shows me that it has the column:

@{{name=\"RenamedColumn\";expression={{$_.Name }} }}

So my thought was that powershell doesn't recognize this renaming... Now my question how do I use something like this from C#? Is there any solution?

like image 680
Raphael Fischer Avatar asked Oct 19 '22 07:10

Raphael Fischer


1 Answers

In PowerShell @{Name="RenamedColumn";Expression={$_.Name}} is not a string but a Hashtable, so in C# you also have to create a Hashtable (or other collection implementing IDictionary) to pass it to Select-Object cmdlet:

new Hashtable{
    {"Name","RenamedColumn"},
    {"Expression",ScriptBlock.Create("$_.Name")}
}

P.S.
If all you want is a renaming, then you does not need ScriptBlock here:

@{Name="RenamedColumn";Expression="Name"}

new Hashtable{
    {"Name","RenamedColumn"},
    {"Expression","Name"}
}
like image 164
user4003407 Avatar answered Oct 28 '22 20:10

user4003407