为什么我的 foreach 变量在每次迭代后都不会在 PowerShell 中输出?

Why is my foreach variable not going to my output in PowerShell after each iteration?

我有 DHCP 脚本,可以在 DHCP 服务器的所有范围内查找匹配的主机名

$list = Get-Content C:\script\HostNameList.txt #Defines content it pulls as list 
$DHServers = Get-DhcpServerInDC #gives variable name for loop

 # Gets all DHCP servers ands scopes 
    foreach ($Server in $DHServers){
        $scopes = Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
    }
$Output = foreach ($hostname in $list) { #Calls each item in list a hostname and sends to output
    if (test-connection -count 1 -computername $hostname -quiet) #With 1 ping, check if hostname is online
    {   
        foreach ($scope in $scopes){ 
            if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$hostName*" ) #compares the hostname to lease to find which scope it is in
            { $scope.name } #return scope it found hostname in
        }
        [PSCustomObject]@{ #Rename varibles in data pull for output file
        Asset = $hostname
        Location = $scope.name #only want the name of the scope
        Status = "Online"
        }
    }   

    else #statement if hostname is not online
    { 
        Write-host "$hostname Is offline, only Last Location is known. $hostname was added to the output file." -BackgroundColor DarkRed
        [PSCustomObject]@{
        Asset = $hostname
        Location = $scope.name #only want the name of the scope, since the name = Location
        Status = "Offline"
        }
    }
}
$Output #show output in powershell
$Output | Export-Csv -Path C:\script\Asset_Result.csv -NoTypeInformation #outputs .csv
Asset    Location         Status
-----     --------         ------
A847    Public Internet      Online
A261    Public Internet      Offline
A201    Public Internet      Online
Asset    Location         Status
-----     --------         ------
A847        FLoor 1         Online
A261      West 1st FL       Offline
A201        Floor 3         Online

我怎样才能在我的应用程序中获得 $scope.name if($scope | ... 语句在每次迭代后转到我的 PSCustomObject?

这个:

foreach ($Server in $DHServers){
  $scopes = Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
}

是——实际上——相当于:

$scopes = Get-DHCPServerv4Scope -ComputerName $DHServers[-1].dnsname #get all scopes

也就是说,你在循环体中不断地重新赋值给同一个变量($scopes),替换之前的值,这样你最终只得到last 循环迭代的结果,对于存储在 $DHServers 中的 last 服务器,即 $DHServers[-1].


最好的解决方案是依靠 PowerShell 将 foreach 等语句用作表达式的能力 其输出 - 甚至是循环的迭代输出 - 被自动收集在 PowerShell 的 [object[]] 数组(具有两个或更多输出)中:

# Collect the output from *all* Get-DHCPServerv4Scope calls.
[array] $scopes = foreach ($Server in $DHServers) {
  Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
}

注意:[array] 类型约束(等同于:[object[]])仅在情况下只有 一个 时才需要输出对象,并且您希望确保收集的输出 始终 一个数组。