Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to export the data to CSV or Excel

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

## 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

>Solution :

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 ....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading