ADAccount非活动帐户通过ADUser问题管道

问题描述 投票:1回答:2

我做了一些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
powershell
2个回答
0
投票

我认为迭代DC和OU,然后只收集非活动用户的最后登录日期最好使用Hashtable对象作为中间存储。

这有助于避免重复条目,并提供比较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

}

希望有所帮助


0
投票

@voilier对不起,我不明白它对你有什么用。粘贴您的代码和Get-ADUser cmdlet需要过滤器值。如果你使用get-help get-aduser -full,你会发现searchbase参数只能与FilterLDAPFilter参数一起使用。不仅如此,它们都不接受管道输入。 Identity参数仅接受按值输入的管道。因此,您需要使用Search-ADAccount @InactiveFilter中的distinguishedname属性作为示例distinguishedname并将其传递给过滤器

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

我用上面的代码替换了你的$users=...部分,现在我看到没有错误和CSV文件成功创建。

用$ this替换你的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
    }
  }

我希望它对你有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.