Built this script out for a friend, and while its not very useful for a DBA its a good example of simply looping through things with foreach and using filtering to get to a result, doing a bit of errorlogging and exporting data on the way.

$dhcpServers = Get-DhcpServerInDC

$r = @()
$e = @()

Foreach ($server in $dhcpServers)
    {
        IF ($server.DnsName -like "RX*")
            {
                TRY 
                    {
                        $s = $server.DnsName
                        $scopes = Get-DhcpServerv4Scope –ComputerName $s

                        foreach ($scope in $scopes) 
                            {
                                $IPOfScope = $scope.ScopeID.IPAddressToString
                                $results =Get-DhcpServerv4Lease -ComputerName $s -ScopeId $IPOfScope -AllLeases | SELECT @{Name="DHCPServer"; Expression={$s}},HostName, AddressState, LeaseExpiryTime
                                $r += $results
                            }
                    }
                CATCH 
                    {
                        $b  =  $error[0] | SELECT @{Name="ServerName"; Expression={$s}}, @{Name="ErrorType"; Expression={$_.Exception.GetType().FullName}}, @{Name="Error"; Expression={$_.Exception.Message}}
                        $e += $b
                    }
            }
    }

<# Output to CSV #>
$r #| Export-Csv -Path C:/temp/Results.csv
$e #| Export-Csv -Path C:/temp/Errors.csv



Advertisements