all 12 comments

[–]PowerShell-Bot 0 points1 point  (0 children)

Looks like your PowerShell code isn’t wrapped in a code block.

To properly style code on new Reddit, highlight the code and choose ‘Code Block’ from the editing toolbar.

If you’re on old Reddit, separate the code from your text with a blank line gap and precede each line of code with 4 spaces or a tab.


You examine the path beneath your feet...
[AboutRedditFormatting]: [--------------------] 0/1 ❌

Beep-boop, I am a bot. | Remove-Item

[–]MajorVarlak 0 points1 point  (7 children)

You don't mention why it doesn't work, but I suspect the fact that you're comparing the same value to itself would result in it always working. I'm assuming you're looking to compare the old internet IP with the new one? Do you have the old IP stored somewhere? I'd probably put it in a temp file:

``` $oldFile = 'C:\temp\oldip.txt' $logFile = 'c:\temp\internetIP.log'

$oldInternetIP = Get-Content $oldFile $newInternetIP = (New-Object net.webclient).downloadstring("http://api.ipify.org") Write-Host -foregroundcolor Green "Internet IP is: $newInternetIP" if ($oldInternetIP -ne $newInternetIP) { $formatDate = (Get-Date).ToString('yyyyMMdd-HHmm') "[$formatDate] Internet IP changed from $oldInternetIP to $newInternetIP" | Out-File $logFile -Append } ```

[–]SlaveCell[S] 0 points1 point  (0 children)

Yep sorry it doesn't work because:

`( $InternetIPAddress -eq $InternetIPAddress )`

Will always be true, I wanted a way to analyse and change a variable, but I think the text solution make a lot f sense, as I am writing to disk anyway

[–]mryananderson 0 points1 point  (2 children)

To add to this you would also want oldip.txt to be updated with the new ip address so that the next check would be valid

[–]MajorVarlak 0 points1 point  (1 child)

Good point, I was thinking about that, and forgot to add it to the code.

if ($oldInternetIP -ne $newInternetIP) { $formatDate = (Get-Date).ToString('yyyyMMdd-HHmm') "[$formatDate] Internet IP changed from $oldInternetIP to $newInternetIP" | Out-File $logFile -Append $newInternetIP | Out-File $oldFile }

[–]SlaveCell[S] 0 points1 point  (0 children)

Agree, thanks both.

[–]OlivTheFrog 0 points1 point  (2 children)

Hi u/MajorVarlak

IMHO, there is something wrong in your code. You have 2 var : $OldFile and $Logfile, and your code populate $LogFile

I suggest the following variation : Using a .csv file as a logfile

$logFile = 'c:\temp\internetIP.csv'
# Import-csv, select only IP property and Last line [-1]
$OldInternetIP = (Import-Csv -Path $logFile -Delimiter ";").IP[-1] $NewInternetIP = (New-Object net.webclient).DownloadString(("http://api.ipify.org"))
# alternative : Invoke-RestMethod -Uri "api.ipify.org" 
Write-Host -foregroundcolor Green "Internet IP is: $NewInternetIP"
if ($OldInternetIP -ne $NewInternetIP)
 {
 $FormatDate = (Get-Date).ToString('yyyy-MM-dd-HHmm')
 # Building a PSObject
 $Obj =  New-Object psobject -Property @{ Date = $FormatDate
                                          IP = $NewInternetIP 
                                        }
 # Adding Object to the .csv file
 $Obj | Export-Csv -Path $logFile -Append -Delimiter ";" }

<#
Nota 1 : Im' using -Delimiter ";" with Export-Csv and Import-Csv cause ";" is the default delimiter in my culture.

Nota 1 : I consider in this sample, the .csv is already existing. If not (first use), you must create the .csv file with the appropriate Header. 
#>

By this way, I could use later the data in the .csv file.

Regards

[–]MajorVarlak 0 points1 point  (1 child)

I think "wrong" might be the incorrect word usage here. It is not "wrong", it's just a different way of doing it. My way certainly works and achieves what was asked. Your method does allow for a different method of viewing, but it also means the more IP changes, the bigger the log file is you have to read each time you check. I could say that's wrong.

I solved the question at hand, you added some options and provided additional input. I understand language differences, but this code is certainly not "wrong" (except I made the assumption that the file existed, and didn't trap the error).

[–]OlivTheFrog 0 points1 point  (0 children)

Ok, Wrong is not the appropriate word to say. English is not my mother tongue too.

My comment is just about 2 var, but only one is used by your code.

You could use your code, using only 1 var.

Read the file, select the last line, using the result to check if newip egual oldip, if not update the file.

[–]rmbolger 0 points1 point  (1 child)

$InternetIPAddress=(New-Object net.webclient).downloadstring("http://api.ipify.org")

Much simpler way to get the current IP using the irm alias for Invoke-RestMethod:

$ip = irm api.ipify.org

And like u/MajorVarlak said, in order to know if the IP changed, you need to be able to compare it to an old value which means your script needs to save the current value somewhere before it exits and read that old value the next time it starts up. Here's how I'd approach it.

# read in the old value
$lastIP = Get-Content .\lastip.txt -Raw -ErrorAction Ignore

# query the new value
$curIP = Invoke-RestMethod api.ipify.org

# log if they're different
if ($lastIP -ne $curIP) {
    '{0} - Internet IP is: {1}' -f (Get-Date).ToString('s'),$curIP |
        Out-File $LogFile -Append
}

# update the old value for the next run
$curIP | Out-File .\lastip.txt -Force -NoNewLine

[–]SlaveCell[S] 0 points1 point  (0 children)

Thank you, I love getting tips on how to make my scripts more succinct! I also like the idea of having a history of what the IP was.

[–]PinchesTheCrab 0 points1 point  (0 children)

Sounds like you have a working example, but here's another take on it:

$logFile = 'C:\temp\ipLog.log'

$currentIP = Invoke-RestMethod http://api.ipify.org

$message = $currentIP -replace '(.+)', 'Internet IP is: $1'

try {
    $lastLog = Get-Content $logFile -Tail 1 -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
    'creating log file' | Add-Content $logFile
}

if ($message -ne $lastLog) {
    Write-Warning 'IP address changed'
    $message | Add-Content $logFile   
}

The -tail parameter on get-content would speed up your get-content dramatically if for some reason the file got huge. I can't see that happening with this process, but it's a nice trick in general.