# Test-Connection Script

**URL:** <https://forums.powershell.org/t/test-connection-script/16318>\
**Category:** PowerShell Help\
**Created:** [April 23, 2021, 3:22pm UTC](https://forums.powershell.org/t/test-connection-script/16318 "2021-04-23T15:22:15Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![TechnoRag](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/technorag/32/1248_2.png) [@TechnoRag](https://forums.powershell.org/u/TechnoRag)\
**Post date:** [April 23, 2021, 3:22pm UTC](https://forums.powershell.org/t/test-connection-script/16318/1 "2021-04-23T15:22:15Z")

</div>

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:

```auto
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 🙂

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 23, 2021, 4:03pm UTC](https://forums.powershell.org/t/test-connection-script/16318/2 "2021-04-23T16:03:21Z")

</div>

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

```auto
$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

}

```

---

<div class="post-metadata">

**Author:** ![TechnoRag](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/technorag/32/1248_2.png) [@TechnoRag](https://forums.powershell.org/u/TechnoRag)\
**Post date:** [April 23, 2021, 4:13pm UTC](https://forums.powershell.org/t/test-connection-script/16318/3 "2021-04-23T16:13:21Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 23, 2021, 5:15pm UTC](https://forums.powershell.org/t/test-connection-script/16318/4 "2021-04-23T17:15:08Z")

</div>

No problem.

> [@TechnoRag](#):
>
> i do not quiet get the syntax

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

---

<div class="post-metadata">

**Author:** ![TechnoRag](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/technorag/32/1248_2.png) [@TechnoRag](https://forums.powershell.org/u/TechnoRag)\
**Post date:** [April 23, 2021, 6:28pm UTC](https://forums.powershell.org/t/test-connection-script/16318/5 "2021-04-23T18:28:21Z")

</div>

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 ^^

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 23, 2021, 8:43pm UTC](https://forums.powershell.org/t/test-connection-script/16318/6 "2021-04-23T20:43:26Z")

</div>

`-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`

---

<div class="post-metadata">

**Author:** ![krzydoug](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/krzydoug/32/1008_2.png) [@krzydoug](https://forums.powershell.org/u/krzydoug)\
**Post date:** [April 23, 2021, 10:13pm UTC](https://forums.powershell.org/t/test-connection-script/16318/7 "2021-04-23T22:13:20Z")

</div>

Love the chained -not

---

<div class="post-metadata">

**Author:** ![TechnoRag](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/technorag/32/1248_2.png) [@TechnoRag](https://forums.powershell.org/u/TechnoRag)\
**Post date:** [April 24, 2021, 8:54am UTC](https://forums.powershell.org/t/test-connection-script/16318/8 "2021-04-24T08:54:58Z")

</div>

At first, thank you for taking time to help me 🙂

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”? 😃

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 24, 2021, 10:19am UTC](https://forums.powershell.org/t/test-connection-script/16318/9 "2021-04-24T10:19:16Z")

</div>

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

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

> [@TechnoRag](#):
>
> I’m not sure if I understood this 100%. I try to explain it in English:

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:

```auto

$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

}

```

---

<div class="post-metadata">

**Author:** ![TechnoRag](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/technorag/32/1248_2.png) [@TechnoRag](https://forums.powershell.org/u/TechnoRag)\
**Post date:** [April 24, 2021, 4:12pm UTC](https://forums.powershell.org/t/test-connection-script/16318/10 "2021-04-24T16:12:36Z")

</div>

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

I definitely need to learn more about switch functions ^^

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:26pm UTC](https://forums.powershell.org/t/test-connection-script/16318/11 "2024-05-16T20:26:32Z")

</div>

Closed on May 16, 2024, 8:26pm UTC


