I am trying to run this command in code and using the AddArgument command for the Select PrimarySMTPAddress
but in code I am getting a error message.
ERROR
System.Management.Automation.ParameterBindingException: 'A positional parameter cannot be found that accepts argument 'Select PrimarySMTPAddress'.'
PowerShell working
Get-DistributionGroupMember -Identity emailaddress -ResultSize Unlimited | Select PrimarySMTPAddress
c# Code
powerShell.AddCommand("get-distributiongroupmember");
powerShell.AddParameter("Identity", distributionGroup.Name);
powerShell.AddArgument("Select PrimarySMTPAddress");
Basically you're missing .AddCommand("Select-Object")
(Note: Select
is an alias of Select-Object
) then you can chain it into .AddArgument("PrimarySMTPAddress")
and it should work properly. I don't have access to Get-DistributionGroupMember
but using a built-in cmdlet and a similar statement as you have:
Get-ChildItem -Filter *.ps1 -File -Recurse |
Select-Object FullName
Would look like this:
public static Collection<PSObject> Invoke()
{
using PowerShell ps = PowerShell.Create()
.AddCommand("Get-ChildItem")
.AddParameters(new Dictionary<string, object>()
{
{ "Filter", "*.ps1" },
{ "File", true },
{ "Recurse", true }
})
.AddCommand("Select-Object")
.AddArgument("FullName");
return ps.Invoke();
}
You might find it easier to bind arguments using .AddParameters
as demonstrated above.
Possibly the statement for your use case would look like this:
public static Collection<PSObject> Invoke()
{
using PowerShell ps = PowerShell.Create()
.AddCommand("Get-DistributionGroupMember")
.AddParameters(new Dictionary<string, object>()
{
{ "Identity", "emailAddress" },
{ "ResultSize", "Unlimited" }
})
.AddCommand("Select-Object")
.AddArgument("PrimarySMTPAddress");
return ps.Invoke();
}
If you want to select more than one property you can do:
.AddCommand("Select-Object")
.AddArgument(new string[] { "PrimarySMTPAddress", "OtherProp", .. });