I am working on a web controller to display and (ultimately) modify domain information for users. Ideally I want userName, full name, status (locked?) and whether they are logged in.
I have gotten this far
# Define the target domain controller
$domainController = "myController"
# Hardcoded credentials (for demonstration purposes only, not recommended in production)
$username = "myUser@my.domain"
$password = ConvertTo-SecureString "MyP@ssw03d!*" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
# Connect to the specified domain controller remotely using hardcoded credentials
$sessionQuery = Get-WmiObject -Class Win32_LogonSession -ComputerName $domainController -Credential $credential
$sessionQuery | ForEach-Object {
Write-Host $_.Properties | ForEach-Object {
$propertyData=[System.Management.PropertyData]$_
Write-Host $($propertyData.Name) $($propertyData.Value)
Write-Host "----------------------"
}
}
But the only data it returns from Powershell is System.Management.PropertyData repeated over and over. Not even the divider is being printed.
I am completely unfamiliar with PowerShell scripting but I haven't been able to find a way to managed this through C#. I am looking for either a solution to this script OR a reference on retrieving what I need from within C#.
Thank you.
After more research I moved from WMI to using DirectorySearcher in C#:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var config = builder.Build();
var admin = config.GetSection("Admin");
// Set up the Directory Entry
DirectoryEntry entry = new DirectoryEntry("LDAP://mcad2.local", admin.GetValue("userName", ""), admin.GetValue("password", ""));
// Set up the Directory Searcher
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(&(objectCategory=person)(objectClass=user))"; // Filter to retrieve only user objects
// Perform the Search
SearchResultCollection r = searcher.FindAll();
This gave me the details I was looking for within the active directory, and can easily be converted to JSON for transport to the web.