Test-Connection Script

Hello guys,

i wrote a script that gives me output if theres no connection to the ip 8.8.8.8 (with time)
now i wanted to enhance the script, so it only gives me one output, if the connection fails and if its restored. Can you give me some advice how to implement that? i am very new to powershell.

The script right now look like this:

while ($true)
{
    if (!(Test-Connection 8.8.8.8 -Quiet -Count 1))
    {
        Write-Host "Connection lost: " -ForegroundColor Red $(Get-Date -Format 'dd.MM.HH HH:mm:ss')
    }

    Start-Sleep -Seconds 10
}

It runs over and over and checks if the connection is failed. The condition shoud be like:
“if you lost the connection, wait till its restored and output it”

The output shoud be something like this then:
“Connection lost: 23.04.2021 17:30:00”
“Connection restored: 23.04.2021 17:35:00”

Please excuse my bad wording and thanks alot for your help :slight_smile:

You can keep track of the connection state with a variable and use a switch statement if the state changes:

$state = $false

while ($true)
{
    if ((Test-Connection 8.8.8.8 -Quiet -Count 1) -ne $state) {

        $state = -not $state
        
        switch ($state) {
            
                $false {Write-Host "Connection lost: " -ForegroundColor Red $(Get-Date -Format 'dd.MM.HH HH:mm:ss')}
                $true  {Write-Host "Connection restored: " -ForegroundColor Green $(Get-Date -Format 'dd.MM.HH HH:mm:ss')}

        }

    }

    Start-Sleep -Seconds 10

}
1 Like

i do not quiet get the syntax, but it works is i wanted to!
Thanks alot :slight_smile:

No problem.

Happy to explain further if you let me know which parts you’re struggling with.

why do you say " -ne $state" and “$state = -not state”. Im not very familiar with programming in generall, so its a bit confusing to me ^^

-ne is the ‘Not equal to’ comparison operator.

The Test-Connection cmdlet, when used with the Quiet parameter, returns a boolean (True/False) value.
$state can also be True or False. At the start of the script, we’ve assigned it the initial value of $false (in PowerShell $true and $false are automatic variables that represent True and False).

In plain English, the if statement says: "if the result of Test-Connection is not the same as (not equal to) the value stored in $state then run the code between the {}

Once we enter the {} the first thing we need to do is to change the value of $state to reflect the result of Test-Connection. Because this can only be True or False, we can ‘flip’ it by negating the current value which we do with the -not logical operator.

e.g. if the value of $state is True then assigning it the value of -not $state (not True), will make $state False. To understand negation, it might be easier to see it in action, so try running the following in a PowerShell prompt and looking at the output.

$true (press Enter)
-not $true (press Enter)
$a = $false (press Enter)
$a (press Enter)
-not $a (press Enter)
-not -not $a (press Enter)

Further reading:
Get-Help about_Comparison_Operators
Get-Help about_Logical_Operators
Get-Help about_Automatic_Variables
Get-Help about_Switch

4 Likes

Love the chained -not

At first, thank you for taking time to help me :slight_smile:

Is $State always a boolean, or does powershell interprets that correctly? I heard that you sometimes need to declare the type ([boolean]) beforehand.

I’m not sure if I understood this 100%. I try to explain it in English:

At first, we say: if test-connection is true (-ne $state) run code {}

Because $state is now True, we need to invert it (-not $state)

If the Test-Connection -Quite is true then output the “$ true […]” line, if it’s not output $false […], correct?

What I don’t get, is why the code doesn’t work if i comment out $state = -not $state and turn around $true and $false
I think i’m missing the big part here…

Maybe you could explain this to me in “English”? :smiley:

Well, it’s a boolean until you assign it a non-boolean value :slight_smile:
If you choose to explicitly declare the type then yes, you guarantee it will always be a boolean.

Not quite.

We don’t really care if the result of Test-Connection is True or False. We only care if the result is different to $state. Think of $state as representing the result of an earlier Test-Connection. If the result of the earlier Test-Connection is different to the result of the current Test-Connection then the state of the connection must have changed. So, if the state of the connection has changed we need to run some code. That code:

Updates $state to reflect the change.
Writes a message to the screen, based on the new value of $state.

I have re-written the script with more verbose commands and variable names. The logic is the same but it might help you understand it better:


$lastConnectionState = $false

while ($true) {

    $currentConnectionState = Test-Connection 8.8.8.8 -Quiet -Count 1

    if ($currentConnectionState -ne $lastConnectionState) {

        $lastConnectionState = $currentConnectionState

        if ($lastConnectionState -eq $false) {

            Write-Host "Connection lost: " -ForegroundColor Red $(Get-Date -Format 'dd.MM.HH HH:mm:ss')

        }

        if ($lastConnectionState -eq $true) {

            Write-Host "Connection restored: " -ForegroundColor Green $(Get-Date -Format 'dd.MM.HH HH:mm:ss')

        }

    }

    Start-Sleep -Seconds 10

}
1 Like

Now I got it! This helped me alot! Thank you so much!

I definitely need to learn more about switch functions ^^