powershellnestedhashtabledhcpscope-id

In Powershell, How can get my if statement to output into a hashtable?


I would like my output to give me a hash table.

$hashtable @{}
If( $scope | Get-DhcpServerV4Lease -ComputerName $server | Where-Object HostName -like "$hostName*") {$hashtable.add($scope.name, $hostname)}

I believe because of how I have things nested I can not get my $hashtable to populate.

$DHServers = Get-DhcpServerInDC #get DHCP info

foreach ($Server in $DHServers){
$scopes = Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
    foreach ($hostname in (Get-Content C:\script\HostNameList.txt)){ #get hostnames from list
        foreach ($scope in $scopes){
        $hastable = @{} #create hash table
        if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$hostName*" ) #compares the hostname to find which lease it is in
        {$hashtable.add($scope.name, $hostname)} # add keys, values to table
        }
    }
}
$hastable

Solution

  • You're re-initializing the hash table inside the loop, so it's going to get clobbered each time. You could try something like this:

    $DHServers = Get-DhcpServerInDC #get DHCP info
    $hashtable = @{} #create hash table
    
    foreach ($Server in $DHServers){
        $scopes = Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
        foreach ($hostname in (Get-Content C:\script\HostNameList.txt)){ #get hostnames from list
            foreach ($scope in $scopes) {
                if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$hostName*" ) { #compares the hostname to find which lease it is in
                    $hashtable.add($scope.name, $hostname) # add keys, values to table
                } 
            }
        }
    }
    
    $hashtable