I often need to retrieve data from Active Directory in many iterations which is very demanding and consumes all the RAM. Processing gradually slows down as well. Off course, a reduced amount of data could help (http://dmitrysotnikov.wordpress.com/2007/07/24/optimize-powershell-performance-and-memory-consumption/). But sometimes it could be better to use a multi-dimensional hash table to temporarily store data from AD rather than reading the data in each iteration. Reading data from a local variable is more effective.
How to add a few attributes to our hash table called ‚ADUsersCache‘ in example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
$SearchRoot = "OU=Users,DC=Domain,DC=Local" $SizeLimit = "0" $ADUsersCache=@{} if ( (Get-PSSnapin -Name quest.activeroles.admanagement -ErrorAction SilentlyContinue) -eq $Null ){ Add-PsSnapin quest.activeroles.admanagement } $ADUsers = Get-QADUser -SearchRoot $SearchRoot -SizeLimit $SizeLimit -DontUseDefaultIncludedProperties ` -IncludedProperties Name, LogonName, LogonScript, PrimarySMTPAddress, Title, Department foreach ($ADUser in $ADUsers) { $Name = $ADuser.Name $LogonName = $ADuser.LogonName $LogonScript = $ADuser.LogonScript $PrimarySMTPAddress = $ADuser.PrimarySMTPAddress $Title = $ADuser.Title $ADUsersCache += @{ "$LogonName" = @{ "Name"="$Name"; "LogonScript"="$LogonScript"; "PrimarySMTPAddress"="$PrimarySmtpAddress"; "Title"="$Title" "Department"="$Department" } } } |
Than i can work with…
1 2 |
$MyProperty = $ADUsersCache.GetEnumerator() | Where-Object {$_.Value.Title -ilike "*sales*"} $MyProperty.Key |