0

I have 3 nested loops and they do the following:

  1. Get scopes from DHCP
  2. Get hostnames from csv file
  3. Compares hostnames and leases, matches are added to a hash table

There are 5 DHCP servers, 100's of scopes and thousands of leases.

What would be a good method to speed this up?

Thank you!

$DHServers = Get-DhcpServerInDC #get DHCP info
$hashtable = @{} #create hash table

foreach ($server in $DHServers){
$scopes = Get-DHCPServerv4Scope -ComputerName $server.dnsname #get all scopes in DHCP   
    
    foreach ($_ in (Import-Csv C:\script\Asset_List.csv | Select-Object -ExpandProperty asset)){ #get hostnames from list          
        
        foreach ($scope in $scopes){            
            if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$_*" ){ #compares the hostname to find which lease it is in
                $scopename=$scope.name #matches give scope name
                $hashtable[$_] = $scopename #when a match is found, add keys and values to table
            } 
        }
    }
}  
  
 
feelsgood
  • 135
  • 14
  • 1
    You can start by importing the CSV only once before the loops instead of once for each server – Doug Maurer Apr 15 '21 at 16:57
  • Thanks for the reply! I gave that a try. It didn't improve the whole script more than a few milliseconds. I thought the way I have it now, would be just as fast since of how it's piped. – feelsgood Apr 15 '21 at 17:02
  • And its not really logic, $scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname into loop.... Always on $server variable into your loop.... – Esperento57 Apr 15 '21 at 17:03
  • @Esperento57 Sorry, but it's unclear to me what you're trying to say. – feelsgood Apr 15 '21 at 17:13
  • 1
    i dont understand why you did it : "$scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname" you dont use $scope property in your pipe – Esperento57 Apr 15 '21 at 17:26
  • My output needs the the name of the scope and Get-DhcpServerv4Lease needs a scopeID parameter. I dont know a better way. – feelsgood Apr 15 '21 at 17:30
  • 1
    If it's working as is, you might try submitting to [codereview.stackexchange.com](https://codereview.stackexchange.com/) for performance tips. At first glance it seems you could make the `Get-DhcpServerV4Lease` run in [parallel jobs](https://stackoverflow.com/questions/43685522/running-tasks-parallel-in-powershell) if it's taking longest. – Rich Moss Apr 15 '21 at 20:12
  • It does work as is, just takes too long. I'm not familiar with parallel jobs. I'll do some reading. Thank you. – feelsgood Apr 15 '21 at 20:21

0 Answers0