求助:编写PowerShell脚本验证主机名与IP对应关系并生成CSV
Hey Tyler, let's get this PowerShell script sorted out for you! Based on what you've described, here's a complete, tested solution that reads your hostname list, validates IP resolution, outputs clear YES/NO statuses, and exports everything to a CSV file.
First, let's clarify: I'm assuming "verify if the IP address is correct" means confirming the hostname successfully resolves to an IP (via DNS). If you need to validate against a specific expected IP, I'll also include a variant for that scenario below.
Basic Version: Check if Hostname Resolves to Any IP
This script reads your hnames.txt, checks DNS resolution for each entry, and logs results:
# Read hostnames from the input file (skip empty lines) $hostnames = Get-Content "hnames.txt" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } # Initialize an array to store our validation results $validationResults = @() foreach ($hostname in $hostnames) { try { # Resolve the hostname to its IP addresses $resolvedIPs = [System.Net.Dns]::GetHostAddresses($hostname) # If we got at least one IP, mark as valid if ($resolvedIPs.Count -gt 0) { $status = "YES" $details = $resolvedIPs[0].IPAddressToString # Show the first resolved IP } else { $status = "NO" $details = "No IP addresses resolved" } } catch { # Catch errors like unresolvable hostnames $status = "NO" $details = "Resolution failed: $($_.Exception.Message)" } # Add the result to our collection $validationResults += [PSCustomObject]@{ Hostname = $hostname ResolvedIP = $details Status = $status } # Print real-time status to the console Write-Host "$hostname -> $status" } # Export results to a CSV file (UTF-8 encoding for compatibility) $validationResults | Export-Csv -Path "HostnameIPValidationResults.csv" -NoTypeInformation -Encoding UTF8 Write-Host "`nAll results exported to HostnameIPValidationResults.csv"
Variant: Validate Against a Specific Expected IP
If your hnames.txt includes paired hostnames and expected IPs (e.g., server01,192.168.1.10 per line), use this version to check if the resolved IP matches the expected one:
# Read and parse hostname/expected IP pairs from the file $hostIPPairs = Get-Content "hnames.txt" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | ForEach-Object { $splitLine = $_.Split(",", 2) [PSCustomObject]@{ Hostname = $splitLine[0].Trim() ExpectedIP = $splitLine[1].Trim() } } $validationResults = @() foreach ($pair in $hostIPPairs) { try { $resolvedIPs = [System.Net.Dns]::GetHostAddresses($pair.Hostname) | Select-Object -ExpandProperty IPAddressToString if ($resolvedIPs -contains $pair.ExpectedIP) { $status = "YES" $details = "Expected IP matches resolved address" } else { $status = "NO" $details = "Resolved IPs: $($resolvedIPs -join ', ')" } } catch { $status = "NO" $details = "Resolution failed: $($_.Exception.Message)" } $validationResults += [PSCustomObject]@{ Hostname = $pair.Hostname ExpectedIP = $pair.ExpectedIP Status = $status Details = $details } Write-Host "$($pair.Hostname) -> $status" } $validationResults | Export-Csv -Path "HostnameIPValidationResults.csv" -NoTypeInformation -Encoding UTF8
Key Notes:
- Lightweight Resolution: The script uses
[System.Net.Dns]::GetHostAddresses()instead ofTest-Connectionbecause it only checks DNS (faster, no ping required). If you need to verify the host is reachable via ping, replace the DNS resolution block withTest-Connection -ComputerName $hostname -Count 1 -Quiet -ErrorAction Stop. - Error Handling: The
try/catchblock catches common issues like unresolvable hostnames or network errors. - CSV Output: The output CSV includes all relevant details (hostname, resolved IP, status) for easy review.
内容的提问来源于stack exchange,提问作者Tyler S

