Reputation: 309
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 = "[email protected]"
$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.
Upvotes: 1
Views: 230
Reputation: 309
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.
Upvotes: 0
Reputation: 174815
Write-Host
is the wrong cmdlet for the job - it prints output directly to the screen, and doesn't produce any standard output that a downstream cmdlet can consume. Drop it completely:
$dcCimSession = New-CimSession -ComputerName $domainController -Credential $credential
$sessionQuery = Get-CimInstance -ClassName Win32_LogonSession -CimSession $dcCimSession
$sessionQuery | ForEach-Object {
# when using the CIM cmdlets, the meta-property you want is `CimInstanceProperties` -
$_.CimInstanceProperties | ForEach-Object {
Write-Host "$($_.Name) $($_.Value)"
Write-Host '----------------------'
}
}
Upvotes: 0