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?
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"}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With