在 Powershell 中,如何让我的 if 语句输出到哈希表中?

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

我希望我的输出给我一个散列 table。

$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

您正在循环内重新初始化散列 table,因此每次都会被破坏。你可以尝试这样的事情:

$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