How to export AD user attributes to a CSV file with powershell Get-ADUser?

The following command exports user attributes to a CSV file:

Exported user attributes are:

  • sAMAccountName
  • displayName
  • distinguishedName
  • employeeID
  • accountExpires
  • whenCreated
  • whenChanged
  • pwdLastSet
  • Password Never Expire
  • Account disabled
  • lastLogonTimestamp
  • lastLogon
Get-ADUser -Filter * -SearchBase "DC=fr,DC=contoso,DC=com" -Properties 
displayName,distinguishedName,sAMAccountName,employeeID,accountExpires,
whenCreated,whenChanged,pwdLastSet,userAccountControl,lastLogonTimestamp,lastLogon 
-Server FR-DC1| 
Select-Object -Property sAMAccountName,displayName,
distinguishedName,employeeID,
@{N='accountExpires';E={[DATETIME]::fromFileTime($_.accountExpires)}},
whenCreated,whenChanged,
@{n='pwdLastSet';e={[DateTime]::FromFileTime($_.pwdLastSet)}},
@{n="Password Never Expire";e={if(($_.userAccountControl[0] -band 65536) -ne 0) {"True"} else {"False"}}},
@{n="Account disabled";e={if(($_.userAccountControl[0] -band 2) -ne 0) {"True"} else {"False"}}},
@{n='lastLogonTimestamp';e={[DateTime]::FromFileTime($_.lastLogonTimestamp)}},
@{n='lastLogon';e={[DateTime]::FromFileTime($_.lastLogon)}} | 
export-csv c:\temp\user_fr.csv -encoding "unicode" 

How to get group members of Active Directory (Powershell script)

This powershell script allow administrator to get group members of Active Directory. It allow to show all members that is user and computers in group.

Function Get-GroupMembers
{
 <#            
	.DESCRIPTION
		Return the members of an an AD group.
	.PARAMETER GroupDN
		The distinguished name of the group to get membership from.
	.EXAMPLE
		Get-GroupMembers -GroupDN "CN=Managers,OU=Groups,DC=fr,DC=contoso,DC=com" | Format-Table -Property cn, objectSID, distinguishedName
 #>
 Param
	(
 $GroupDN = "CN=Managers,OU=Groups,DC=fr,DC=contoso,DC=com"
	)
 Begin
	{
		$Group = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($GroupDN)")
		$UserAccounts = @()
	}
 Process
	{
		$Members = $Group.member
		
		If ($Members -ne $Null)
		{
			foreach ($User in $Members)
			{
				$UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)")
				If ($UserObject.objectCategory.Value.Contains("Group"))
				{
				}
				Else
				{
					$CurrentUser = New-Object -TypeName PSObject -Property @{
						name = $UserObject.name
						cn = $UserObject.cn
						distinguishedName = $UserObject.distinguishedName
						nTSecurityDescriptor = $UserObject.nTSecurityDescriptor
						objectSID = $UserObject.objectSID
					}
				}
			$UserAccounts += $CurrentUser
			}
		}
	}
 End
	{
		Return $UserAccounts
	}
}