1

I have written a script to check the nslookup for each server and export the details to Excel, but my script is looking but I am not able to export the output when I export I a getting empty data.

Please help me to export the data to Excel

CODE

## Loop through each server for Nslookup
foreach ($Server in $Servers)
{
    $Addresses = $null
    try {
        $Addresses = [System.Net.Dns]::GetHostAddresses("$Server").IPAddressToString
    }
    catch { 
        $Addresses = "Server IP cannot resolve"
    }
    foreach($Address in $addresses) {
        #write-host $Server, $Address
         $Server_Name = $Server
         $IP_Address = $Address                 
    } 
  } 
$result | Export-Excel -Path $FileName -AutoSize -BoldTopRow -FreezeTopRow -TitleBold -WorksheetName Server_Nslookup_Details
chandu
  • 35
  • 3
  • 16

1 Answers1

2

Your inner foreach loop is producing no output, just assigning values to the 2 variables ($Server_Name and $IP_Address):

foreach($Address in $addresses) {
    $Server_Name = $Server
    $IP_Address = $Address
}

You likely meant to construct a new object instead:

$result = foreach($Server in $Servers) {
    $addresses = try {
        [System.Net.Dns]::GetHostAddresses($Server).IPAddressToString
    }
    catch {
        "Server IP cannot resolve"
    }
    foreach($address in $addresses) {
        [pscustomobject]@{
            Server    = $Server
            IPAddress = $address
        }
    }
}

$result | Export-Excel ....
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • Can you help me like how to add color to specific text in the Excel output file – chandu Apr 05 '22 at 18:21
  • @chandu please ask a new question for that, adding what have you tried and your expected result – Santiago Squarzon Apr 05 '22 at 18:28
  • i tried something nothing is working out, I already created a new discussion https://superuser.com/questions/1714686/how-to-add-color-to-specific-text-in-excel-output-file-using-powershell – chandu Apr 05 '22 at 18:31
  • @chandu im guessing youre looking for something like this: https://stackoverflow.com/a/71721884/15339544 (if so, I recommend you to move your question to SO instead of SuperUser) – Santiago Squarzon Apr 05 '22 at 18:52