Powershell

通過命令行查找 ip 地理位置

  • July 25, 2017

我一直在嘗試拼湊一個快速而骯髒的腳本來返回一堆 IP 地址的地理位置。

我正在使用 freegeoip.net 並且找不到與 cmd 行等效的快速 wget ,因此為此使用 powershell 腳本,從我的批處理文件中呼叫它(或者至少,嘗試,我認為這就是我失敗的地方)。

命令行是:

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"
)

(第一行需要跳過,因為包含標題,而不是 IP)

geolocation.ps1 是:

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

我希望這會給我一個包含每個 IP 返回的 CSV 的文件夾,然後我可以用副本 E:\DATA\IPs*.txt alltheips.txt 將其整理到一個文件中,然後將該文件載入到另一個文件中應用程序使用。

這個(顯然)雜湊是從我在Google上搜尋並在這里和那裡收集的內容混合在一起的,但是,(顯然)我實際上並不知道我在這裡做什麼,所以任何對缺失部分的幫助將不勝感激!

簡而言之,我所追求的是獲取我的 IP 地址列表(我有一個帶有標題的文本文件,然後每一行都是一個新 IP,文件的長度為 x 並且每次執行都會有所不同 - 偶爾它將是空的,所以如果我可以檢查文件的長度並且它只包含標題以跳過該過程,那將很方便)。對照 freegeoip.net 檢查這些 IP,並將它們提供的數據整理到一個文件中,以便在一個程序中使用,該程序將使用者的位置與我通過 IP 持有的關於他們的其他數據相關聯。

乾杯!

將整個腳本放入腳本中。在這種情況下,無需將 PowerShell 包裝在批處理文件中。實際上,這樣做會損失很多,因為 PowerShell 是物件導向的。

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

引用自:https://serverfault.com/questions/799930