通过ADUser问题发布的ADAccount无效帐户

时间:2019-04-16 08:19:38

标签: powershell

我做了一些PowerShell脚本来查找AD中闲置的用户,这些用户已有90天的历史了,它遍历所有DC并获得LastLogon属性。我还需要只有ADUser才能带来的一些额外属性。在$users = Search-ADAccount行中使用管道运行脚本时出现错误。

Import-Module ActiveDirectory

function Get-ADUsersLastLogon() {
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $OUs = @()
  $OU += "ou=Users-A,ou=Users,ou=Items,dc=mydc,dc=com"
  $OU += "ou=Users-B,ou=Users,ou=Items,dc=mydc,dc=com"

  $time = 0
  $exportFilePath = "c:\tmp\lastLogon-test $(get-date -f dd-MM-yyyy).csv"
  $columns = "name;username;whencreated;whenchanged;DNname;datetime"
  #InactiveTest
  $InactiveFilter = @{
      UsersOnly = $true
      AccountInactive = $true
      TimeSpan = New-Timespan -Days 90
  }
  #EndInactiveTest
  Out-File -FilePath $exportFilePath -Force -InputObject $columns

  foreach ($OU in $OUs) {
    $users = Search-ADAccount @InactiveFilter |
             Get-ADUser -Filter * -SearchBase $OUs -Property displayName, whenCreated, whenChanged
    foreach ($user in $users) {
      foreach($dc in $dcs) { 
        $hostname = $dc.HostName
        $currentUser = Get-ADUser $user.SamAccountName |
                       Get-ADObject -Server $hostname -Properties lastLogon
        if ($currentUser.LastLogon -gt $time) {
          $time = $currentUser.LastLogon
        }
      }

      $dt = [DateTime]::FromFileTime($time)
      $row = $user.displayName + ";" + $user.SamAccountName + ";" +
             $user.whenCreated + ";" + $user.whenChanged + ";" +
             $user.distinguishedName + ";" + $dt

      Out-File -FilePath $exportFilePath -Append -NoClobber -InputObject $row

      $time = 0
    }
  }
}

Get-ADUsersLastLogon

2 个答案:

答案 0 :(得分:0)

@voilier抱歉,我不知道它如何为您工作。粘贴代码,Get-ADUser cmdlet需要过滤器值。如果使用get-help get-aduser -full,则会看到searchbase参数只能与FilterLDAPFilter参数一起使用。除此之外,它们都不接受管道输入。 Identity参数仅按值接受管道输入。因此您需要使用Search-ADAccount @InactiveFilter中的distinguishedname属性作为专有名称,并将其传递给过滤器

$users = Search-ADAccount @InactiveFilter | %{Get-ADUser -filter {distinguishedname -eq $_.distinguishedname}  -SearchBase $OU -Property displayName, whenCreated, whenChanged}

我用上面的代码替换了$users=...部分,现在我看不到任何错误,并且CSV文件已成功创建。

以此替换$ ous中的foreach $ ou并检查csv文件。它可以在我的计算机上工作

Foreach ($ou in $ous){
$users = (Search-ADAccount @InactiveFilter | %{Get-ADUser -filter {distinguishedname -eq $_.distinguishedname} -SearchBase $OU -Property displayName, whenCreated, whenChanged})  
    foreach ($user in $users) {
      foreach($dc in $dcs) { 
        $hostname = $dc.Name
        $last_logon_time=((Get-ADUser $user.SamAccountName | Get-ADObject -Server "$hostname" -Properties lastLogon) |?{$_.lastlogon -gt $time}) | select -ExpandProperty lastlogon
      }
      $dt = [DateTime]::FromFileTime("$last_logon_time")
      $row = $user.displayName + ";" + $user.SamAccountName + ";" +
             $user.whenCreated + ";" + $user.whenChanged + ";" +
             $user.distinguishedName + ";" + $dt
      Out-File -FilePath $exportFilePath -Append -NoClobber -InputObject $row

      $last_logon_time = 0
    }
  }

希望对您有帮助

答案 1 :(得分:0)

我认为最好使用Hashtable对象作为中间存储来遍历DC和OU,然后仅收集非活动用户的上次登录日期。

这有助于避免重复输入,并有机会比较LastLogonDate属性。

对于最终输出,它使用一个称为Export-Csv的cmdlet。

(未经测试的)代码下方:

function Get-ADUsersLastLogon {
    # get your ad domain
    $DomainName = (Get-ADDomain).DNSRoot
    # get all DC hostnames as string array
    $DCs = Get-ADDomainController -Filter * -Server $DomainName | Select-Object -ExpandProperty Hostname
    # create an array of OU distinghuished names used as SearchBase
    $OUs = "OU=Users-A,OU=Users,OU=Items,DC=mydc,DC=com", "OU=Users-B,OU=Users,OU=Items,DC=mydc,DC=com"
    $exportFilePath = "c:\tmp\lastLogon-test $(Get-Date -Format dd-MM-yyyy).csv"

    $InactiveFilter = @{
        UsersOnly       = $true
        AccountInactive = $true
        TimeSpan        = New-Timespan -Days 90
    }

    # use a lookup Hashtable to eliminate duplicates and collect only the latest logon dates
    $lookup = @{}

    # loop through the list of dc's
    foreach ($dc in $DCs) {
        # loop through the list of OU's
        foreach ($ou in $OUs) {
            $users = Search-ADAccount @InactiveFilter -SearchBase $ou -Server $dc
            foreach($user in $users) {
                # get the properties we want from the AD User. 
                # using the PowerShell property names, we get the dates already converted into DateTime objects.
                $usr = Get-ADUser -Identity $user.DistinguishedName -Server $dc -Properties DisplayName, Created, Modified, LastLogonDate |
                        Select-Object @{Name = 'Name'; Expression = {$_.DisplayName}},
                                        SamAccountName,
                                        @{Name = 'WhenCreated'; Expression = {$_.Created}},
                                        @{Name = 'WhenChanged'; Expression = {$_.Modified}},
                                        @{Name = 'DistinguishedName'; Expression = {$_.DistinguishedName}},
                                        @{Name = 'LastLogon'; Expression = {$_.LastLogonDate}}
                if ($usr) {
                    if ($lookup.ContainsKey($($user.DistinguishedName))) {
                        # we have collected this user before 
                        $lastLogon = $lookup[$($user.DistinguishedName)].LastLogon
                        if ($lastLogon) {
                            if (($usr.LastLogon) -and $lastLogon -lt $usr.LastLogon) {
                                # only store this new instance if the $user.LastLogon property is of a later date
                                $lookup[$($user.DistinguishedName)] = $usr
                            }
                        }
                    }
                    else {
                        # this is a new user, so add the object to the HashTable
                        $lookup[$($user.DistinguishedName)] = $usr
                    }
                }
                else {
                    # should never happen..
                    Write-Warning "User $($user.SamAccountName) not found."
                }
            }
        }
    }

    # export the objects contained in the $lookup Hashtable as CSV
    ($output = foreach ($key in $lookup.Keys) {
        $lookup.$key
    }) | Export-Csv -Path $exportFilePath -NoTypeInformation -Delimiter ';' -Encoding UTF8 -Force

}

希望有帮助