如何加速PowerShell中嵌套的DHCP foreach循环?

如何加速PowerShell中嵌套的DHCP foreach循环?,powershell,optimization,foreach,hostname,dhcp,Powershell,Optimization,Foreach,Hostname,Dhcp,我有3个嵌套循环,它们执行以下操作: 从DHCP获取作用域 从csv文件获取主机名 比较主机名和租约,将匹配项添加到哈希表中 有5台DHCP服务器、100个作用域和数千个租约 有什么好方法可以加快速度 谢谢大家! $DHServers = Get-DhcpServerInDC #get DHCP info $hashtable = @{} #create hash table foreach ($server in $DHServers){ $scopes = Get-DHCPServerv4

我有3个嵌套循环,它们执行以下操作:

  • 从DHCP获取作用域
  • 从csv文件获取主机名
  • 比较主机名和租约,将匹配项添加到哈希表中
  • 有5台DHCP服务器、100个作用域和数千个租约

    有什么好方法可以加快速度

    谢谢大家!

    $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
                } 
            }
        }
    }  
      
     
    

    您可以在循环之前只导入一次CSV,而不是每个服务器导入一次。谢谢您的回复!我试了一下。它对整个脚本的改进并没有超过几毫秒。我想我现在拥有的方式,会和它的管道一样快。而且它不是真正的逻辑,$scope | Get-DhcpServerV4Lease-ComputerName$server.dnsname into loop。。。。始终将$server变量放入循环中…我不明白您为什么这样做:“$scope | Get-DhcpServerV4Lease-ComputerName$server.dnsname”您不在管道中使用$scope属性如果它按原样工作,您可以尝试提交以获取性能提示。乍一看,如果花费的时间最长,您似乎可以让
    Get-DhcpServerV4Lease
    运行。