hopefully somebody can troubleshoot a simple piece of code that I've been messing around with.
I'll open by stating I am NOT a coder and never really done much powershell.
The issue is that at first, this was working, returning the LastLogonTimeStamp as expected.
Now when I run it I get no output in this column at all.
I'm pretty sure it's something stupid I'm overlooking but I cant figure it out.
Like I said – I've literally no experience at this – I don't know what half the code means.
Could anybody please help me out?
# Script to list member of VDI Desktop Users Group
# and export details to c:\VDIlastlogon.csv file
# Rob@x.com 24/11/14'
# Function get-NestedMembers
# List the members of a group including all nested members of subgroups
Import-Module ActiveDirectory
function get-NestedMembers ($group){
if ($group.objectclass[1] -eq 'group') {
write-verbose "Group $($group.cn)"
$Group.member |% {
$de = new-object directoryservices.directoryentry("LDAP://$_")
if ($de.objectclass[1] -eq 'group') {
get-NestedMembers $de
}
Else {
$de
}
}
}
Else {
Throw "$group is not a group"
}
}
# get a group
$group = new-object directoryservices.directoryentry("LDAP://CN=VDI Desktop Users,ou=Groups,ou=x,ou=uk,dc=uk,dc=x,dc=com")
# Get all nested members and send to CSV file
get-NestedMembers $group|FT @{l="First Name";e={$_.givenName}},@{l="Last Name";e={$_.sn}},@{l="Last Logon";e={[datetime]::FromFileTime($_.ConvertLargeItegerToInt64($_.lastLogonTimestamp[0]))}},sAMAccountName | tee c:\VDILastLogon.csv
#Send CSV file to mail recipient
$PSEmailServer = "mail.x.net"
$smtpServer = "mail.x.net"
$file = "c:\VDILastLogon.csv"
$att = new-object Net.Mail.Attachment($file)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient ($smtpServer)
$msg.From = "x@x.com"
$msg.To.Add("x@x.com")
$msg.Subject = "User logon report from VDI Solution"
$msg.Body = "Please find attached the most recent user logon report"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
Best Answer
If you import the AD powershell module you shouldn't need to use extra directoryservices objects (at least not on this occasion). You can use the
Get-ADGroupMember
cmdlet with-Resursive
and it should find your nested users also.Edit: I added
-Server
arguments to the AD cmdlets so you can specify particular DCs. Timestamp attributes may differ (they do across my 12 DCs as well). Check this blog for a decent writeup.This gets the last logon time and is a bit easier to read: