I am stuck with a simple task and need community help, please. I'm running a PowerShell script in a C# code and need to convert the output to a dictionary. The code is
private void button_datecheck_Click(object sender, EventArgs e)
{
var script = "Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties \"DisplayName\", \"msDS-UserPasswordExpiryTimeComputed\" | Select-Object -Property \"Displayname\",@{Name=\"ExpiryDate\";Expression={[datetime]::FromFileTime($_.\"msDS-UserPasswordExpiryTimeComputed\")}}";
var ps = PowerShell.Create().AddScript(script);
var temp_list = ps.Invoke().ToList();
using (TextWriter tw = new StreamWriter("C:\\c#\\test_output.txt"))
{
foreach (dynamic item in temp_list)
{
tw.WriteLine(item);
}
}
Not sure if PSObject can be directly converted to a dictionary, so converted it to a List first (Also, to have a look at what kind of output I do have from PS) Output looks like
@{Displayname=Name Surname; ExpiryDate=1/02/2022 9:24:48 am} @{Displayname=Name1 Surname1; ExpiryDate=2/02/2023 11:20:27 am}
And here I am stuck, do not know how to convert it to a dictionary or maybe there is a way to convert it directly to a dictionary without using lists?
Thanks for any help
CodePudding user response:
Are powershell something that the c# program uses often, or is it for this specific task? I'm asking this because using pwsh for 'just' getting users seemes like really tedious and uneccecary.
HOWEVER.. if you really want to do this, possibly the best way to handle this is to output from powershell as json and import to c#. you can do this by appending |convertto-json
before outputting to any file. this way you deserialize and serialize to objects
that you can handle.
possibly the best way is to use some sort of c# ldap library. even the activedirectory
module uses somekind of c# library: How can I get a list of users from active directory?
CodePudding user response:
Get-ADUser
outputs ADUser
instances. I would drop the Select-Object
part of your script's pipeline and use C# to access the properties you want.
I don't have a domain to test against but it should look something like this...
var script = "Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties \"DisplayName\", \"msDS-UserPasswordExpiryTimeComputed\"";
var ps = PowerShell.Create().AddScript(script);
var userList = ps.Invoke().ToList();
foreach (dynamic user in userList)
{
Dictionary<string, object> userProperties = new Dictionary<string, object>();
userProperties["DisplayName"] = user["displayName"].Value;
userProperties["ExpiryDate"] = DateTime.FromFileTime((long) user["msDS-UserPasswordExpiryTimeComputed"].Value);
// Use userProperties for this user...
}
Even better would be to reference the Microsoft.ActiveDirectory.Management
assembly in your C# project and then you can access user
directly as an ADUser
without using dynamic
.