简体   繁体   中英

How do I create a powershell script to pull active directory usernames, account they are a member of and lastlogondate?

This is what I have so far but I'm having no luck. What do you all think?

Get-ADUser -LDAPFilter "(name=*)" -SearchScope Subtree `
  -SearchBase "OU=adminaccounts,OU=Managed Objects,DC=testdomain,DC=Com" ` |
  % {
    $user = $_
    $user | Get-ADPrincipalGroupMembership | 
    Select @{N="User";E={$user.sAMAccountName}},
           @{N="Group";E={$_.Name}},
           @{N="Last‌​Logon";E={[DateTime]::FromFileTime($user.LastLogon)}}
  } |
  Select User,Group,LastLogon |
  Export-Csv C:\temp\report.csv -nti

LastLogon is not among the properties that Get-ADUser returns by default, unlike Name and SamAccountName . You need to explicitly tell the cmdlet to include that property:

Get-ADUser -LDAPFilter "(name=*)" -SearchScope Subtree `
  -SearchBase "OU=adminaccounts,OU=Managed Objects,DC=testdomain,DC=Com" `
   | ...

Also replace $_.LastLogon with $user.LastLogon inside the first select statement, because the current object variable ( $_ ) in the nested pipeline has a different value than you expect (the principal group of the user):

... | select ...,@{N="Last‌​Logon";E={[DateTime]::FromFileTime()}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM