最佳实践 - 如果匹配返回结果

时间:2018-06-09 06:53:44

标签: powershell

使用案例

以下脚本将被放置在计划任务中,以便在我的公共IP地址更改时通知我

IF匹配条件不是正确的行为

如果IP地址发生变化并将其输出到主机,最佳匹配方式是什么?

代码

$ip = Invoke-RestMethod http://ipinfo.io/json | select -ExpandProperty ip
$date = (get-date).date
$value = "{0} - {1}" -f ($date),($ip)
Add-Content -Value $value -Path "C:\users\Sumeet\Documents\WindowsPowerShell\ip.txt"
$file = Get-Content -Path "C:\users\Sumeet\Documents\WindowsPowerShell\ip.txt"

if ($file | Select-String -Pattern $ip) {
clear-host
write-host "Match found at $_ your public IP interface has changed"
}

文件输出

Date - IP

9/06/2018 12:00:00 AM - 121.211.177.20

9/06/2018 12:00:00 AM - 121.211.177.20

输出

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为类似的东西会更有帮助,正如@LotPings建议的那样。只有在有更改时才应更新文件,并根据需要跟进通知。

另请注意,IP的更改可以随时进行,但您的计划任务只会在计划运行时通知您。

$ip = Invoke-RestMethod http://ipinfo.io/json | select -ExpandProperty ip
$date = (get-date).date
$value = "{0} - {1}" -f ($date),($ip)

$file = Get-Content -Path "E:\Code\powershell\myPS\2018\Jun\checkPublicIP\ip.txt"

if ($file | Select-String -Pattern $ip) {
    Write-Host "IP is not changed"
}
else {
    #Adding current IP to the file
    Add-Content -Value $value -Path "E:\Code\powershell\myPS\2018\Jun\checkPublicIP\ip.txt"

    #Add more code as needed for notification / email / alert. 
}

答案 1 :(得分:1)

使用csv文件时,IMO的处理更容易,因为在导入时会分配列/属性。

由于我的语言环境不支持AM / PM的日期分隔符/tt,因此我必须使用CultureInfo对象。

## Q:\Test\2018\06\09\SO_50771712.ps1
$File = "$Env:USERPROFILE\Documents\WindowsPowerShell\ip.csv"
$CIUS = New-Object System.Globalization.CultureInfo("en-US")

$Actual = [PSCustomObject]@{
    Date = (get-date).ToString("d/M/yyyy hh:mm:ss tt",$CIUS)
    IP   = (Invoke-RestMethod http://ipinfo.io/json).ip
}
if (!(Test-Path $File)){'"Date","IP"'|Set-Content $File}

$Last=Import-Csv $File|Sort-Object {[DateTime]$_.Date}|Select-Object -Last 1

If ($Last.ip -ne $Actual.ip){
    Write-Host ("Last ip : {0} from: {1}" -f $LAst.IP,$Last.date)
    Write-Host ("New  ip : {0} from: {1}" -f $Actual.IP,$Actual.date)
    Export-Csv $File -InputObject $Actual -Append -NoTypeInformation
}

示例输出:

> Q:\Test\2018\06\09\SO_50771712.ps1
Last ip : 92.123.13.83 from: 9/6/2018 09:19:21 PM
New  ip : 92.123.13.84 from: 9/6/2018 09:34:59 PM

> gc $file
"Date","IP"
"9/6/2018 08:51:00 PM","92.123.13.82"
"9/6/2018 09:19:21 PM","92.123.13.83"
"9/6/2018 09:34:59 PM","92.123.13.84"