1

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
feelsgood
  • 135
  • 14

1 Answers1

2

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
WaitingForGuacamole
  • 3,744
  • 1
  • 8
  • 22
  • 1
    I found changing the last line up a little will eliminate errors if there are duplicates in the table ```$hashtable[$hostame] = $scope.name #add keys, values to table``` – feelsgood Apr 15 '21 at 16:48