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
CodePudding user response:
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 ....