В Powershell, как получить мой оператор if для вывода в хеш-таблицу?

Я хотел бы, чтобы мой результат дал мне хеш-таблицу.

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

Я считаю, что из-за того, что у меня есть вложенные вещи, я не могу получить свой $hashtable заселить.

      $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

1 ответ

Решение

Вы повторно инициализируете хеш-таблицу внутри цикла, поэтому каждый раз она будет затираться. Вы можете попробовать что-то вроде этого:

      $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
Другие вопросы по тегам