WAN IP更改脚本

时间:2018-11-17 12:50:09

标签: powershell

我正在尝试记录和比较我的WAN IP地址更改。

我发现了一个非常有用的脚本(对不起,作者不记得了,谢谢!),用于将IP保存在txt文件中,然后我对其进行了一些更改以满足自己的需要。现在,我想每次都搜索txt文件,并在屏幕上添加一条消息,指出IP从未使用过或已被重复使用。

我不是程序员,不胜感激。

下面的脚本。

$ipDetectionUrl = "https://wtfismyip.com/text"  
$IPAddFile = "C:\IP.txt" #absolute path to file that stores the old IP 
record  
$Request = Invoke-WebRequest $ipDetectionUrl  
$IP_new = ($Request.Content.Trim())  
Write-Host "Current IP address: [$IP_new]"  
#Check if old IP record exists  
If(Test-Path "$IPAddFile")  
{  
#Get old IP  
$IP_old = Get-Content "$IPAddFile" -Tail 1  
#Compare IPs  
if(-not($IP_new -eq $IP_old))  
{  
Write-Host "Old IP address: [$IP_old]"              
#Overwrite and update new IP  
$IP_new |  Out-File $IPAddFile -Append  
}  
else  
{"No change"}  
}  
else  
{  
#Create new, as file not found  
$IP_new |  Out-File $IPAddFile  
"File created"  
}  

1 个答案:

答案 0 :(得分:1)

一个If可以有多个elseif,但有其他条件,但只能有一个else

使用脚本块缩进的正确格式可以更好地呈现代码
自己也可以阅读/理解。

## Q:\Test\2018\11\17\SO_53351417.ps1

$ipDetectionUrl = "http://api.ipify.org"
$IPAddFile = "C:\IP.txt" #absolute path to file that stores the old IP record

$IP_new = (Invoke-WebRequest $ipDetectionUrl).Content.Trim()
Write-Host "Current IP address: [$IP_new]"

#Check if old IP record exists
If(!(Test-Path $IPAddFile)){
    #Create new, as file not found
    $IP_new | Out-File $IPAddFile -Encoding default
    "File {0} created" -f $IPAddFile
}

#Get all old IPs
$IP_old = Get-Content $IPAddFile

# 1st compare last IP, then other IPs
if($IP_new -eq $IP_old[-1]){
    "No change"
} else {
    if ($IP_old -contains $IP_new) {
        $LinesAgo = $IP_old.Length - [array]::IndexOf($IP_old,$IP_new') ######
        $wshell = New-Object -ComObject Wscript.Shell
        $wshell.Popup($IP_new,0,"IPaddress reused",0x0)|Out-Null
        Write-Host "Old IP address reused [$LinesAgo] lines ago: [$IP_new]" #####
    } else {
        Write-Host "New IP address: [$IP_new]"
    }
    # Append new (or reused) IP
    $IP_new |  Out-File $IPAddFile -Append  -Encoding default
}

我使用http://api.ipify.org是因为它比IPv6地址更喜欢IPv4。