Question

I am building an application in C# that can run PowerShell commands. Currently I am in the stage where I got the user properties into PSObject.

I want to get specific details from the user properties but I don't know how.

enter image description here

The problem is that inside the cmdlet I have the property BaseObject and inside it I have the properties GivenName and Surname.

I want to get GivenName into parameter but I don't know what kind of parameter. I tried to "Copy Expression" and I received:

((Microsoft.ActiveDirectory.Management.ADUser)(cmdlet.BaseObject)).GivenName

But it is not recognized.

No such class:
Microsoft.ActiveDirectory.Management.ADUser

Do you have an idea how can I get the GivenName property into the parameter?

Was it helpful?

Solution

I am little bit unsure on what you mean by get value GivenName into a parameter. If you just want the given name from the results then it is easy to get.

var givenName = cmdlet.Properties["GivenName"].Value;

If you looking to get all the properties then you can get it in PSMemberInfoCollection

 PSMemberInfoCollection<PSPropertyInfo> props = psObject.Properties;                       
 props.ToList().ForEach(x => {
   Console.WriteLine("Name: {0}, Value: {1}", x.Name,x.Value);                        
 });

If you are trying to convert PSObject into ADUser then you will have to load the assembly Microsoft.ActiveDirectory.Management in your c# sharp code, then create an instance of ADUser from the PSObject

Edit1:

So if you want to get the groups or a particular group by index then. Again this just purely based upon hacks. Use all the code with caution. Anyways you can use dynamic keyword to do something interesting. First you can get the GivenName property just like that. And then your MemberOf property will give you a ValueList which is of type Collection and you get property by an index or you can Enumerate over all the properties available to you.

dynamic adUser = psObject.BaseObject;
Console.WriteLine("GivenName: {0}, Surname: {1}",adUser.GivenName.ToString(),adUser.Surname.ToString());

dynamic memberof = psObject.Properties["MemberOf"].Value;    
var firstGroup = memberof.ValueList[0].ToString();
var allGroups = memberof.ValueList;
foreach (var item in allGroups)
{
   Console.WriteLine(item.ToString());
}

OTHER TIPS

In Powershell did you remember to reflect the assembly before running your command.

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.ActiveDirectory.Management');((Microsoft.ActiveDirectory.Management.ADUser)(cmdlet.BaseObject)).GivenName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top