如何解决在 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
解决方法
您正在循环内重新初始化哈希表,因此每次都会被破坏。你可以试试这样的:
$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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。