简体   繁体   中英

Powerhsell - Need to resolve IPs

I can export the file containing the original data as either a json, xml, or csv. I chose JSON.

The JSON output looks like the below.

{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":
"31.170.162.203",
"description":
"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":
"37.193.217.222",
"description":
"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":
"46.17.63.169",
"description":
"test3"}
,
]
}

$input = Get-Content 'C:\Users\e\Desktop' -raw | ConvertFrom-Json

$iplist = $input.entry.'ip-netmask'


foreach ($ip in $iplist)   #for each line in the file...

{
    $hostnames = $null

    try {

        $hostnames = [System.Net.Dns]::GetHostByAddress("$ip").Hostname   #...resolve the ip

    }
     catch [System.Management.Automation.MethodInvocationException] {

          $hostnames = "Server IP cannot resolve."
    }

    catch {

        $hostnames = "unknown error."

    }

    if ($hostnames -ne "Server IP cannot resolve.") {

        $ip -replace $ip, $hostnames

    } else {

        Write-Host $ip
    }
}

output:

31.170.165.68
31.170.162.203
l37-193-217-222.novotelecom.ru

This tells me it is replacing the resolved IPs, and keeping any original IPs that weren't resolved. This is exactly what I want

I ended up figuring out how to resolve them through further research, trial, and error.

Thing 1- The posted json is not properly formatted.

Thing 2 -

Read in the json string, csv, xml file data and pass the IPA to the .Net class or DNS cmdlets to resolve them

One Example (as there are other ways)...

(@'
{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":"31.170.162.203",
"description":"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":"37.193.217.222",
"description":"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":"46.17.63.169",
"description":"test3"}
]
}
'@ | 
ConvertFrom-Json | 
Select-Object -ExpandProperty entry).'ip-netmask' | 
ForEach {
    $PSItem
    [System.Net.Dns]::GetHostEntry("$PSItem").HostName
}

#Results
...
37.193.217.222
l37-193-217-222.novotelecom.ru
...

or this way

(@'
{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":"31.170.162.203",
"description":"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":"37.193.217.222",
"description":"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":"46.17.63.169",
"description":"test3"}
]
}
'@ | 
ConvertFrom-Json | 
Select-Object -ExpandProperty entry) | 
ForEach {
    $PSItem.'@name'
    $PSItem.'ip-netmask'
    $PSItem.'description'
    [System.Net.Dns]::GetHostEntry("$($PSItem.'ip-netmask')").HostName
}


# Results
...
37.193.217.222
37.193.217.222
test2
l37-193-217-222.novotelecom.ru
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM