Powershell – Lookup ip geolocation via command line

command-line-interfacegeolocationippowershellwindows-command-prompt

I've been trying to piece together a quick and dirty script to return the geolocation of a bunch of IP addresses.

I'm using freegeoip.net and couldn't find a quick wget equivalent for cmd line so using a powershell script for that, calling it from my batchfile (or at least, trying, and I think that's where I'm failing).

The command line is:

for /F "tokens=* usebackq delims=" %a in ("E:\DATA\02.ips.txt") do (
set /a N+=1
 powershell -command "E:\DATA\Resources\geolocation.ps1 %a"
)

(first row needs to be skipped as contains header, not an IP)

the geolocation.ps1 is:

wget freegeoip.net/csv/$args[0] -OutFile "E:\DATA\IPs\$args[0].txt"

I'm hoping this will give me a folder of the returned CSV's for each IP, which I can then collate into one file with a copy E:\DATA\IPs*.txt alltheips.txt and that file will then be loaded into another app for use.

This (evidently) hash is mashed together from what I've googled and picked up here and there, but, (clearly) I don't actually know what I'm doing here so any help in the missing piece would be grateful!

In short, what I'm after, is taking my list of IP address (I have a text file that has a header, and then each row is a new IP, the files is of x length and will vary on each run – occasionally it will be empty, so would be handy if I can check the length of the file and if it just contains the header to skip the process).
Check those IP's against freegeoip.net and collate the data they supply into one file to use in a program that will associate the location of users to other data I hold about them via the IP.

Cheers!

Best Answer

Put the whole script in the script. No need to wrap PowerShell in a batch file in this case. Actually, you lose a lot in doing so, since PowerShell is object oriented.

# for the filename, this is a string
# quotes needed if there's a space, 
# use single quotes unless the string is an expression which needs evaluation
#
# Import-CSV builds an array of objects from the contents of the csv
# using the first row as a header
# in your case the objects will be strings which are IP addresses
# 
# For your own benefit, make sure the ip address column 
# (only one columnt per your post) has a simple title in the first row

$IPList = Import-CSV E:\DATA\02.ips.txt 

# the Foreach command is a for loop used with arrays or collections to loop through all the members

Foreach ($IPAddress in $IPList) {
    # In PowerShell, wget is an alias for Invoke-WebRequest
    # the $() wrapper around the $IPAddress.ipaddress is to force evaluation of that expression
    Invoke-WebRequest "freegeoip.net/csv/$($IPAddress.ipaddress)" -OutFile "E:\DATA\IPs\$($IPAddress.ipaddress).txt"
    }