I'm trying to do some remote PowerShell commands to an Exchange-Server. Now I'm having problems executing ScriptBlocks in Parameters.
My C# Code looks like:
List<object> parameters = new List<object>()
{
"DisplayName","Guid","ManagedBy",
new Hashtable()
{
{"Name","NameRename"},
{"Expression","Name"}
}
};
powershell.AddCommand("Get-DistributionGroup");
powershell.AddParameter("ResultSize", "unlimited");
powershell.AddCommand("Select-Object");
powershell.AddParameter("Property", parameters);
powershell.AddParameter("ExpandProperty", "ManagedBy");
parameters = new List<object>()
{
"DisplayName","Guid","NameRename",new Hashtable()
{
{"Name","ManagedByGuid"},
{"Expression",ScriptBlock.Create("($_.ManagedBy).ObjectGuid -join ','")}
}
};
powershell.AddCommand("Select-Object");
powershell.AddParameter("Property", parameters);
Collection<PSObject> result = powershell.Invoke();
I know there are a few things missing (runspace open f.e.) but this code should only be an exapmle because my actualy code works dynamically so you couldn't see the real command. What so ever... My result shows me null for the column "ManagedByGuid". The rename in the first parameters only works when there is no script at all in the expression (as soon as I set the expression to ScriptBlock.Create("$_.Name")
it also delivers null values ).
So it seems that powershell isn't executing the scriptblock instead it s only evaluating the string in plain without scripting...
When I instead of seperating the commands pass one finished script as string to the powershell it works just fine.... example:
powershell.AddScript("Get-DistributionGroup -ResultSize unlimited | Select-Object -Property Alias,Guid,DisplayName,WhenChanged,WhenCreated,@{name=\"NameRename0\";expression={$_.Name}},ManagedBy -expand ManagedBy |Select-Object Alias,Guid,DisplayName,WhenCreated,WhenChanged,NameRename0,@{Name=\"ObjectGuid\";expression={ ($_.ManagedBy).ObjectGuid -join ',' }} -unique");
I could also use this method but first I don't want to redo all of my code and second the scripblock should also work?
Does anyone got an idea why this isn't working...??