【问题标题】:In Powershell, How can get my if statement to output into a hashtable?在 Powershell 中,如何让我的 if 语句输出到哈希表中?
【发布时间】:2021-07-07 20:00:08
【问题描述】:

我希望我的输出给我一个哈希表。

$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

【问题讨论】:

    标签: powershell nested hashtable dhcp scope-id


    【解决方案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
    

    【讨论】:

    • 我发现如果表中有重复,稍微更改最后一行将消除错误$hashtable[$hostame] = $scope.name #add keys, values to table
    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2021-10-15
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多