How to use Powershell to make ADSI queries

412 views Asked by At

I am currently trying to get a list of user object properties for a number of accounts in my environment. However, this requires querying some ADSI properties, and I am not entirely sure how to get this to work, even after doing some self-guided study.

What I am doing is using something like the below to create a foreach loop to get some details on these users, but I additionally need for it to iterate through LDAP queries for a bunch of separate ADSI properties (e.g. AllowLogon, MaxConnectionTime, TerminalServicesWorkDirectory) and add the outputs to my resultant CSV. I believe that this will look something like this, but I'm not sure how to make the LDAP/ADSI queries in the middle work properly:

# Choose the OU containing the accounts to be searched:
$OU = "OU=Accounts,DC=domain,DC=local"

# Set up the ADUser search base:
$Accounts = Get-ADuser -Filter * -Searchbase $OU

#Define CSV output based off of results of ForEach loop
$Output = ForEach($Account in $Accounts){
    Get-ADUser -identity $Account -Properties * |
    Select-Object Name,GivenName

#This is where I am unsure on how to get these queries to work properly
    $User = [ADSI]("LDAP://" + $account.distinguishedname)
    $user.psbase.InvokeGet("AllowLogon")
    $user.psbase.InvokeGet("MaxConnectionTime")
    $user.psbase.InvokeGet("TerminalServicesWorkDirectory")

}

#Write output to CSV
$Output | Export-CSV C:\Temp\Output.csv

Can anyone set me down the correct path to getting these to properly populate a CSV? Thanks!

1

There are 1 answers

1
Mathias R. Jessen On

[...] but I additionally need for it to iterate through LDAP queries for a bunch of ...

You really don't - Get-ADUser can fetch the desired attribute values up front - you just have to use the correct names for the attributes:

# Fetch all user accounts with the required attributes
$Accounts = Get-ADuser -Filter * -Searchbase $OU -Properties Name,GivenName,msTSAllowLogon,msTSMaxConnectionTime,msTSWorkDirectory

# Rename the RDS attributes to something slight more easily-readable
$Output = $Accounts |Select Name,GivenName,@{Name='AllowLogon';Expression='msTSAllowLogon'},@{Name='MaxConntectionTime';Expression='msTSMaxConnectionTime'},@{Name='TerminalServicesWorkDirectory';Expression='msTSWorkDirectory'}

# Write output to CSV
$Output | Export-CSV C:\Temp\Output.csv