如何将此 Powershell 脚本更改为按 OU 而不是用户身份进行搜索

如何将此 Powershell 脚本更改为按 OU 而不是用户身份进行搜索

我有下面这个想要使用的脚本,但是它被设置为搜索单个用户。

我希望有一种方法能够通过 OU 来指定,但是也能够在任意级别选择 OU?

例如“OU=Clients”将获取该文件夹中的所有用户以及其下子文件夹中的所有用户。 - 我认为 powershell 已经这样做了,但不确定。

Function Get-LastLogon {
    <#
    .SYNOPSIS
    Returns LastLogon information
    .DESCRIPTION
    Queries the LastLogin information for a user across domain controllers and returns the highest (latest) value
    .EXAMPLE
    Get-LastLogon User
    .EXAMPLE
    Get-LastLogon -Identity User
    .EXAMPLE
    Get-ADUser User | Get-LastLogon
    .EXAMPLE
    Get-LastLogon User1, User2
    .PARAMETER users
    List of users - pipeline can be used
    #>
    
    [CmdletBinding()]
    param
    (
    [Parameter(Position= 0,
                Mandatory=$True,
                    ValueFromPipeline=$True,
                        HelpMessage='What user would you like to find the last logon for?')]
    $identity
    )
    
    Begin {}
    
    Process {
    
        Foreach ($account in $identity) {
    
            $dateStamp = $null
            $domainController =$null

            Get-ADDomainController -Filter * | Foreach {

                $dc = $_.HostName
                
                $lastLogon = (Get-ADUser $account -Properties LastLogon -server $dc | Select-Object Name,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}).Lastlogon
                
                If ($dateStamp -le $lastlogon)
                    {
                    $dateStamp = $lastlogon
                    $domainController = $dc
                    }
                
            } # End of ForEach
        
            $properties = @{
            Name=$account;
            LastLogon=$dateStamp;
            DomainController=$domainController}
        
            New-Object -TypeName PSObject -Prop $properties
        
        } # End of ForEach

    } # End of Process
        
    End {}          
            
} # End of Function
```c

答案1

下面是使用 OU 作为参数的示例,然后指定-SearchBase获取 OU 及其子文件夹中的所有 AD 用户:

Function Get-LastLogon {
  param(
    [string]$OUName
  )

  # Get all matching OUs on any level
  $OUs = Get-ADOrganizationalUnit -Filter "Name -like '$OUName'"
  $DCs = Get-ADDomainController -Filter *

  # Get all users from each OU from each DC
  $ADUsers = Foreach ($OU in $OUs) {
    Foreach ($DC in $DCs.HostName) {
      Get-ADUser -SearchBase $OU.DistinguishedName -Filter * -Properties LastLogon -server $dc | 
        Select-Object Name,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}
    }
  }

  # return most recent LastLogon date for each user
  $ADUsers | 
    Group Name | 
    Select Name,@{n='LastLogon';e={$_.Group.LastLogon | sort -desc | select -First 1}}
}  ## End function

Get-LastLogon -OUName 'Clients'

相关内容