PSSpeedTest.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
function Get-SpeedTestConfig {
    <#
        .SYNOPSIS
        Get the default server configurations for Internet and Local speed test servers.

        .DESCRIPTION
        Get the default server configurations for Internet and Local speed test servers.

        .EXAMPLE
        Get-SpeedTestConfig
    #>


    [CmdletBinding()]
    Param()

    try {
        Write-Verbose -Message 'Getting content of config.json and returning as a PSCustomObject.'
        $config = Get-Content -Path "$PSScriptRoot\config.json" -ErrorAction 'Stop' | ConvertFrom-Json

        $config = [PSCustomObject] @{
            DefaultInternetServer = $config.defaultInternetServer.defaultServer;
            DefaultInternetPort   = $config.defaultInternetServer.defaultPort;
            DefaultLocalServer    = $config.defaultLocalServer.defaultServer;
            DefaultLocalPort      = $config.defaultLocalServer.defaultPort;
        }

        return $config
    } catch {
        throw "Can't find the JSON configuration file. Use 'Set-SpeedTestConfig' to create one."
    }
}
function Install-SpeedTestServer {
    <#
        .SYNOPSIS
        Configures the local computer as an iPerf3 server.

        .DESCRIPTION
        Configures iPerf3 as a constantly-listening service on the local computer.
        
        .PARAMETER Port
        The port number that the iPerf3 server will listen on.
        If not specified, the default port '5201' will be used.

        .PARAMETER PassThru
        Returns the object returned by "Get-Process -Name 'iperf3' -ErrorAction 'SilentlyContinue'".

        .EXAMPLE
        Install-SpeedTestServer
        Sets up the local computer as an iPerf3 server listening on default iPerf port 5201.

        .EXAMPLE
        Install-SpeedTestServer -Port 5555
        Sets up the local computer as an iPerf3 server listening on port 5555.

        .EXAMPLE
        Install-SpeedTestServer -Port 5555 -PassThru
    #>


    [CmdletBinding()]
    Param (
        [ValidateNotNullOrEmpty()]
        [String]
        $Port = '5201',
        [Switch]
        $PassThru
    )

    $timeout = 30 # Seconds

    if (!(Test-Administrator)) {
        throw 'You are not running as administrator. Please re-run this function after opening PowerShell as administrator.'
    }

    Write-Verbose -Message "Setting up iPerf3 server on local machine on port $Port."
    Install-ChocolateyGetProvider
    Install-iPerf3
    Set-iPerf3Port -Port $Port
    Set-iPerf3Task -Port $Port

    $timeoutTimer = [Diagnostics.Stopwatch]::StartNew()
    $processTest = $false
    while ($timeoutTimer.Elapsed.TotalSeconds -lt $timeout) {
        $getProcessResult = Get-Process -Name 'iperf3' -ErrorAction 'SilentlyContinue'
        if ($getProcessResult) {
            Write-Verbose -Message "iPerf3 Server started on port $Port."
            $processTest = $true
            break
        } else {
            Start-Sleep -Seconds 3
        }
    }
    $timeoutTimer.Stop()

    if (!($processTest)) {
        throw "iPerf3 Server failed to start on port $Port. Timeout of $timeout seconds reached."
    }

    if ($PassThru) {
        return $getProcessResult
    }
}
function Invoke-SpeedTest {
    <#
        .SYNOPSIS
        Starts a bandwidth test over the internet or on the local private network.

        .DESCRIPTION
        Starts a bandwidth test with iPerf3 over the internet against a public iPerf3 server, or on the local private network against a previously-configured iPerf3 server.

        .PARAMETER Internet
        Forces the bandwitdth test to run over the internet against a public iPerf3 server.
        If a default public iPerf3 server is not specified in the configuration file, the user will be prompted to run Set-SpeedTestConfig.

        .PARAMETER Local
        Forces the bandwidth test to run over the local network against a locally-accessible iPerf3 server.
        If a default server is not specified in the configuration file, the user will be prompted to run Set-SpeedTestConfig.

        .PARAMETER Server
        The hostname or IP address of a server that is running iPerf3 as a listening service.

        .PARAMETER Port
        The port on the iPerf3 server that iPerf3 is listening on.
        This will run the local iPerf3 client on the same port as they must match on the client and the server.
        If Server is specified and Port is not, the default port '5201' will be used.

        .EXAMPLE
        Invoke-SpeedTest -Internet
        Runs a bandwidth test against default public iPerf3 server that is stored in the configuration.
        If there is no stored default, you will be prompted to set one.

        .EXAMPLE
        Invoke-SpeedTest -Local
        Runs a bandwidth test against default local iPerf3 server that is stored in the configuration.
        If there is no stored default, you will be prompted to set one.

        .EXAMPLE
        Invoke-SpeedTest -Server local.domain.com
        Runs a bandwidth test against iPerf3 server 'local.domain.com' on default port '5201'.

        .EXAMPLE
        Invoke-SpeedTest -Server 20.19.57.21 -Port 7777
        Runs a bandwidth test against iPerf3 server '20.19.57.21' on port '7777'.

        .EXAMPLE
        Invoke-SpeedTest -Server 20.19.57.21 -Port 7777
        Runs a bandwidth test against iPerf3 server '20.19.57.21' on port '7777'.
        Returns the send/receive speeds as a PSCustomObject with properties.
    #>


    [CmdletBinding()]
    Param (
        [Parameter(ParameterSetName = 'Internet')]
        [Switch]
        $Internet,
        [Parameter(ParameterSetName = 'Local')]
        [Switch]
        $Local,
        [Parameter(Mandatory = $true,
            ParameterSetName = 'Specified')]
        [ValidateNotNullOrEmpty()]
        [String]
        $Server,
        [Parameter(ParameterSetName = 'Specified')]
        [ValidateNotNullOrEmpty()]
        [String]
        $Port
    )

    Write-Verbose -Message 'Starting speed test.'

    Install-ChocolateyGetProvider
    Install-iPerf3

    $defaultPort = '5201'
    $config = Get-SpeedTestConfig -ErrorAction 'SilentlyContinue'
    $command = "iperf3.exe "
    $usedServer = ''
    $usedPort = ''

    switch ($PSCmdlet.ParameterSetName) {
        'Internet' {
            Write-Verbose -Message 'Defaulting to stored Internet speed test server settings.'
            if (!($config.DefaultInternetServer)) {
                throw 'No default Internet server configured - run Set-SpeedTestConfig.'
            } else {
                $usedServer = $config.DefaultInternetServer
                $command = $command + "-c $usedServer "
                if ($config.DefaultInternetPort) {
                    $usedPort = $config.DefaultInternetPort
                    $command = $command + "-p $usedPort "
                } else {
                    $usedPort = $defaultPort
                    $command = $command + "-p $usedPort "
                }
            }
            break
        }
        'Local' {
            Write-Verbose -Message 'Defaulting to stored Local speed test server settings.'
            if (!($config.DefaultLocalServer)) {
                throw 'No default Local server configured - run Set-SpeedTestConfig.'
            } else {
                $usedServer = $config.DefaultLocalServer
                $command = $command + "-c $usedServer "
                if ($config.DefaultLocalPort) {
                    $usedPort = $config.DefaultLocalPort
                    $command = $command + "-p $usedPort "
                } else {
                    $usedPort = $defaultPort
                    $command = $command + "-p $usedPort "
                }
            }
            break
        }
        'Specified' {
            Write-Verbose -Message "Server: $Server and port: $Port specified manually."
            $usedServer = $Server
            $command = $command + "-c $usedServer "
            if ($Port) {
                $usedPort = $Port
                $command = $command + "-p $usedPort "
            } else {
                $usedPort = $defaultPort
                $command = $command + "-p $usedPort "
            }
            break
        }
        Default {
            Write-Error -Message 'ParameterSet not identified.'
        }
    }

    $command = $command + "-f m -J"

    Write-Verbose -Message "Executing command: $command"

    $resultsJSON = Invoke-Expression -Command $command
    $resultsPS = $resultsJSON | ConvertFrom-Json

    if ($resultsPS.error) {
        Write-Warning -Message "Problem occurred: $($resultsPS.error)"
        $megabitsPerSecSent = 0
        $megabitsPerSecReceived = 0
    } else {
        Write-Verbose -Message 'Speed test successful; calculating mbps and returning PSCustomObject.'
        $megabitsPerSecSent = (($resultsPS.end.sum_sent.bits_per_second) / 1000000.0).ToInt32($null)
        $megabitsPerSecReceived = (($resultsPS.end.sum_received.bits_per_second) / 1000000.0).ToInt32($null)
    }

    $returnObj = New-Object -TypeName 'PSCustomObject' @{
        megabitsPerSecSent     = $megabitsPerSecSent;
        megabitsPerSecReceived = $megabitsPerSecReceived;
    }

    return $returnObj
}
function Remove-SpeedTestServer {
    <#
        .SYNOPSIS
        Removes iPerf3 server configuration from the local computer.

        .DESCRIPTION
        Removes iPerf3 server configuration from the local computer.
        This includes the iPerf3 package, firewall rules, and scheduled task.

        .EXAMPLE
        Remove-SpeedTestServer
        Decommissions the local iPerf3 server.
    #>


    [CmdletBinding()]
    Param ()

    $timeout = 30 # Seconds

    if (!(Test-Administrator)) {
        throw 'You are not running as administrator. Please re-run this function after opening PowerShell as administrator.'
    }

    Write-Output 'Decommissioning local iPerf3 server.'

    # Remove scheduled task before stopping process to prevent auto-trigger
    Remove-iPerf3Task

    Write-Verbose -Message 'Stopping iPerf3 process.'
    try {
        Get-Process -Name 'iperf3' | Stop-Process
    } catch {
        Write-Verbose -Message 'iPerf3 process not found - no action taken.'
    }

    Remove-iPerf3Port
    Remove-iPerf3

    $timeoutTimer = [Diagnostics.Stopwatch]::StartNew()
    $processTest = $false
    while ($timeoutTimer.Elapsed.TotalSeconds -lt $timeout) {
        $getProcessResult = Get-Process -Name 'iperf3' -ErrorAction 'SilentlyContinue'
        if (!$getProcessResult) {
            Write-Verbose -Message 'iPerf3 process does not exist.'
            $processTest = $true
            break
        } else {
            Start-Sleep -Seconds 3
        }
    }
    $timeoutTimer.Stop()

    if (!($processTest)) {
        throw "iPerf3 process still running even though decommission was attempted. Timeout of $timeout seconds reached."
    }
}
function Set-SpeedTestConfig {
    <#
        .SYNOPSIS
        Set the default server configurations for Internet and Local speed test servers.

        .DESCRIPTION
        Set the default server configurations for Internet and Local speed test servers.
        Convert parameter values to appropriate PSCustomObject and write to the JSON configuration file.

        .PARAMETER InternetServer
        The server that will be utilized when running "Invoke-SpeedTest -Internet".

        .PARAMETER InternetPort
        The port that will be utilized when running "Invoke-SpeedTest -Internet".

        .PARAMETER LocalServer
        The server that will be utilized when running "Invoke-SpeedTest -Local".

        .PARAMETER LocalPort
        The port that will be utilized when running "Invoke-SpeedTest -Local".

        .EXAMPLE
        Set-SpeedTestConfig -InternetServer "test.public.com" -InternetPort "5201"
        Sets the default Internet speed test server to "test.public.com" on port "5201".

        .EXAMPLE
        Set-SpeedTestConfig -InternetServer "test.public.com"
        Sets the default Internet speed test server to "test.public.com".
        When running a speed test, the last saved Internet port will be utilized, or the default port "5201".

        .EXAMPLE
        Set-SpeedTestConfig -InternetPort "5201"
        Sets the default Internet speed test port to "5201".
        Requires a previously-saved Internet speed test server.

        .EXAMPLE
        Set-SpeedTestConfig -LocalServer "test.local.com" -LocalPort "5201"
        Sets the default Local speed test server to "test.local.com" on port "5201".

        .EXAMPLE
        Set-SpeedTestConfig -LocalServer "test.local.com"
        Sets the default Local speed test server to "test.local.com".
        When running a speed test, the last saved Local port will be utilized, or the default port "5201".

        .EXAMPLE
        Set-SpeedTestConfig -Local "5201"
        Sets the default Local speed test port to "5201".
        Requires a previously-saved Local speed test server.
    #>


    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [String]
        $InternetServer,
        [ValidateNotNullOrEmpty()]
        [String]
        $InternetPort,
        [ValidateNotNullOrEmpty()]
        [String]
        $LocalServer,
        [ValidateNotNullOrEmpty()]
        [String]
        $LocalPort
    )

    try {
        Write-Verbose -Message 'Trying Get-SpeedTestConfig before Set-SpeedTestConfig.'
        $config = Get-Content -Path "$PSScriptRoot\config.json" -ErrorAction 'Stop' |
            ConvertFrom-Json
        Write-Verbose -Message 'Stored config.json found.'
    } catch {
        Write-Verbose -Message 'No configuration found - starting with empty configuration.'
        $jsonString = @'
{
    "defaultLocalServer" : {
        "defaultServer" : "",
        "defaultPort" : ""
    },
    "defaultInternetServer" : {
        "defaultServer" : "",
        "defaultPort" : ""
    }
}
'@

        $config = $jsonString |
            ConvertFrom-Json
    }

    # Detailed parameter validation against current configuration
    if ($InternetPort -and (!($InternetServer)) -and (!($config.defaultInternetServer.defaultServer))) {
        throw 'Cannot set an Internet port with an empty InternetServer setting.'
    }
    if ($LocalPort -and (!($LocalServer)) -and (!($config.defaultLocalServer.defaultServer))) {
        throw 'Cannot set a Local port with an empty LocalServer setting.'
    }

    if ($InternetServer) {$config.defaultInternetServer.defaultServer = $InternetServer}
    if ($InternetPort) {$config.defaultInternetServer.defaultPort = $InternetPort}
    if ($LocalServer) {$config.defaultLocalServer.defaultServer = $LocalServer}
    if ($LocalPort) {$config.defaultLocalServer.defaultPort = $LocalPort}

    Write-Verbose -Message 'Setting config.json.'
    $config |
        ConvertTo-Json |
            Set-Content -Path "$PSScriptRoot\config.json"
}
function Install-ChocolateyGetProvider {
    <#
        .SYNOPSIS
        Installs the ChocolateyGet package provider/source on this computer.

        .DESCRIPTION
        Installs the ChocolateyGet package provider/source on this computer forcefully.

        .PARAMETER PassThru
        Returns the object returned by "Get-PackageProvider -Name 'ChocolateyGet' -ErrorAction 'SilentlyContinue'".

        .EXAMPLE
        Install-ChocolateyGetProvider

        .EXAMPLE
        Install-ChocolateyGetProvider -PassThru
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param (
        [Switch]
        $PassThru
    )

    Write-Verbose -Message 'Checking for existence of ChocolateyGet provider.'
    $toReturn = Get-PackageProvider -Name 'ChocolateyGet' -ErrorAction 'SilentlyContinue'
    if ($toReturn) {
        Write-Verbose -Message 'Chocolatey package provider/source already installed.'
        if ($PassThru) {
            return $toReturn
        } else {
            return
        }
    }

    $PackageProviderParams = @{
        Name        = 'ChocolateyGet';
        Scope       = 'CurrentUser';
        Force       = $true;
        ErrorAction = 'SilentlyContinue';
        Confirm     = $false;
    }

    Write-Verbose -Message 'Installing ChocolateyGet PackageProvider as it was not found.'
    if ($PSCmdlet.ShouldProcess($PackageProviderParams['Name'], 'Install-PackageProvider')) {
        Install-PackageProvider @PackageProviderParams | Out-Null
    }
    
    $toReturn = Get-PackageProvider -Name 'ChocolateyGet' -ErrorAction 'SilentlyContinue'
    if ($toReturn) {
        Write-Verbose -Message 'Chocolatey package provider/source successfully installed.'
    } else {
        throw 'ChocolateyGet failed to install or was not installed. Message: {0}' -f $error[0].Exception.message
    }

    if ($PassThru) {
        return $toReturn
    }
}
function Install-iPerf3 {
    <#
        .SYNOPSIS
        Installs the latest version of iPerf3 on this computer.

        .DESCRIPTION
        Installs the latest version of iPerf3 on this computer from the ChocolateyGet package source.

        .PARAMETER PassThru
        Returns the object returned by "Get-Package -Name 'iperf3' -ProviderName 'ChocolateyGet' -ErrorAction 'SilentlyContinue'".

        .EXAMPLE
        Install-iPerf3

        .EXAMPLE
        Install-iPerf3 -PassThru
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param (
        [Switch]
        $PassThru
    )

    try {
        Write-Verbose -Message 'Checking for existing iperf3 package.'
        Import-PackageProvider -Name 'ChocolateyGet' -ErrorAction 'Stop'
        $toReturn = Get-Package -Name 'iperf3' -ProviderName 'ChocolateyGet' -Force -ErrorAction 'SilentlyContinue'

        if ($toReturn) {
            Write-Verbose -Message 'iPerf3 package already installed.'
            if ($PassThru) {
                return $toReturn
            } else {
                return
            }
        }
    } catch {
        if (!(Get-PackageProvider -ListAvailable -Name 'ChocolateyGet' -ErrorAction 'SilentlyContinue')) {
            Write-Verbose -Message 'ChocolateyGet package provider not found; installing.'
            try {
                Install-ChocolateyGetProvider
            } catch {
                $PSCmdlet.ThrowTerminatingError($_)
            }
        }
    }

    Write-Verbose -Message 'Importing ChocolateyGet package provider and installing iperf3 package as it was not found.'
    Import-PackageProvider -Name 'ChocolateyGet'

    $PackageParams = @{
        Name         = 'iperf3';
        ProviderName = 'ChocolateyGet';
        Force        = $true;
        ErrorAction  = 'SilentlyContinue';
        Confirm      = $false;
    }
    if ($PSCmdlet.ShouldProcess($PackageParams['Name'], 'Install-Package')) {
        Install-Package @PackageParams |
            Out-Null
    }

    $toReturn = Get-Package -Name 'iperf3' -ProviderName 'ChocolateyGet' -ErrorAction 'SilentlyContinue'
    if ($toReturn) {
        Write-Verbose -Message 'iPerf3 package installed.'
    } else {
        throw 'iPerf3 failed to install or was not installed. Message: {0}' -f $error[0].Exception.message
    }

    if ($PassThru) {
        return $toReturn
    }
}
function Remove-iPerf3 {
    <#
        .SYNOPSIS
        Removes the iPerf3 Chocolatey package from this computer.

        .DESCRIPTION
        Removes the iPerf3 package from this computer as installed from the ChocolateyGet package source.

        .EXAMPLE
        Remove-iPerf3
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param ()

    Write-Verbose -Message "Removing 'iperf3' package."

    try {
        if ($PSCmdlet.ShouldProcess('iperf3', 'Uninstall-Package')) {
            Get-Package -Name 'iperf3' -ProviderName 'ChocolateyGet' |
                Uninstall-Package
        }
    } catch {
        Write-Verbose -Message "Package 'iperf3' not found as installed by ChocolateyGet provider - no action taken."
    }
}
function Remove-iPerf3Port {
    <#
        .SYNOPSIS
        Removes the local firewall rules for the port that iPerf3 was listening on.

        .DESCRIPTION
        Removes the local firewall rules for the port that iPerf3 was listening on.
        This will remove the configured firewall rules from Windows Firewall.

        .EXAMPLE
        Remove-iPerf3Port
    #>


    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param()

    Write-Verbose -Message 'Removing inbound and outbound iperf3 firewall rules.'

    try {
        if ($PSCmdlet.ShouldProcess('iperf3 Inbound/Outbound Firewall Rules', 'Remove-NetFirewallRule')) {
            Get-NetFirewallRule -DisplayName 'iPerf3 Server Inbound TCP Rule' |
                Remove-NetFirewallRule
            Get-NetFirewallRule -DisplayName 'iPerf3 Server Outbound TCP Rule' |
                Remove-NetFirewallRule
        }
    } catch {
        Write-Verbose -Message 'Firewall rules not found - no action taken.'
    }
}
function Remove-iPerf3Task {
    <#
        .SYNOPSIS
        Removes the iPerf3 server scheduled task that was previously configured.

        .DESCRIPTION
        Removes the iPerf3 server scheduled task that was previously configured.
        Stops the task and then unregisters it.

        .EXAMPLE
        Remove-iPerf3Task
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param()

    Write-Verbose -Message 'Unregistering iPerf3 scheduled task.'

    try {
        if ($PSCmdlet.ShouldProcess('iperf3 Server Scheduled Task', 'Unregister-ScheduledTask')) {
            Get-ScheduledTask -TaskName 'iPerf3 Server' |
                Unregister-ScheduledTask
        }
    } catch {
        Write-Verbose -Message 'Scheduled task not found - no action taken.'
    }
}
function Set-iPerf3Port {
    <#
        .SYNOPSIS
        Set the local firewall rules for the port that iPerf3 will listen on.

        .DESCRIPTION
        Set the local firewall rules for the port that iPerf3 will listen on.
        This will set inbound/outbound Allow TCP on the given port.

        .PARAMETER Port
        The port that iPerf3 will listen on.

        .PARAMETER PassThru
        Returns the objects returned by 'New-NetFirewallRule' for both the inbound and outbound rules, in an array.

        .EXAMPLE
        Set-iPerf3Port -Port '5201'

        .EXAMPLE
        Set-iPerf3Port -Port '5201' -PassThru
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Port,
        [Switch]
        $PassThru
    )

    Write-Verbose -Message 'Setting inbound and outbound iperf3 firewall rules.'

    $FirewallInboundParams = @{
        DisplayName = 'iPerf3 Server Inbound TCP Rule';
        Direction   = 'Inbound';
        LocalPort   = $Port;
        Protocol    = 'TCP';
        Action      = 'Allow';
        ErrorAction = 'SilentlyContinue';
    }

    $FirewallOutboundParams = @{
        DisplayName = 'iPerf3 Server Outbound TCP Rule';
        Direction   = 'Outbound';
        LocalPort   = $Port;
        Protocol    = 'TCP';
        Action      = 'Allow';
        ErrorAction = 'SilentlyContinue';
    }

    if ($PSCmdlet.ShouldProcess('iperf3 Inbound/Outbound Firewall Rules', 'New-NetFirewallRule')) {
        $inboundResult = New-NetFirewallRule @FirewallInboundParams
        $outboundResult = New-NetFirewallRule @FirewallOutboundParams
    }

    if ($inboundResult -and $outboundResult) {
        Write-Verbose -Message 'iPerf3 server port firewall rules set.'
    } else {
        throw 'iPerf3 server port firewall rules could not be set. Message: {0}' -f $error[0].Exception.message
    }

    if ($PassThru) {
        return @($inboundResult, $outboundResult)
    }
}
function Set-iPerf3Task {
    <#
        .SYNOPSIS
        Configures the iPerf3 server scheduled task that will listen on the given port.

        .DESCRIPTION
        Configures the iPerf3 server scheduled task that will listen on the given port.
        Sets the scheduled task to run on startup.

        .PARAMETER Port
        The port that iPerf3 will listen on.

        .PARAMETER PassThru
        Returns the object returned by "Get-ScheduledTask -TaskName 'iPerf3 Server' -ErrorAction 'SilentlyContinue'".

        .EXAMPLE
        Set-iPerf3Task -Port "5201"
    #>

    
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Port,
        [Switch]
        $PassThru
    )

    Write-Verbose -Message 'Gathering scheduled task settings.'
    $actionParams = @{
        Execute  = (Get-Command -Name 'iperf3.exe' | Select-Object -ExpandProperty 'Source');
        Argument = "-s -D -p $Port";
    }

    $taskAction = New-ScheduledTaskAction @actionParams
    $taskTrigger = New-ScheduledTaskTrigger -AtStartup
    $taskPrincipal = New-ScheduledTaskPrincipal -GroupId 'BUILTIN\Administrators' -RunLevel Highest
    $taskSettings = New-ScheduledTaskSettingsSet
    
    $taskParams = @{
        Action      = $taskAction;
        Description = 'iPerf3 Speed Test Server';
        Principal   = $taskPrincipal;
        Settings    = $taskSettings;
        Trigger     = $taskTrigger;
        ErrorAction = 'SilentlyContinue';
    }

    $task = New-ScheduledTask @taskParams

    if ($PSCmdlet.ShouldProcess('iperf3 Server Scheduled Task', 'Register-ScheduledTask')) {
        Register-ScheduledTask -InputObject $task -TaskName 'iPerf3 Server' -ErrorAction 'SilentlyContinue' |
            Out-Null
    }

    $toReturn = Get-ScheduledTask -TaskName 'iPerf3 Server' -ErrorAction 'SilentlyContinue'

    if ($toReturn) {
        Start-ScheduledTask -TaskName 'iPerf3 Server'
        Write-Verbose -Message 'Scheduled task for iPerf3 server registered and started.'
    } else {
        throw 'Scheduled task for iPerf3 server was not registered. Message: {0}' -f $error[0].Exception.message
    }

    if ($PassThru) {
        return $toReturn
    }
}
function Test-Administrator {
    <#
        .SYNOPSIS
        Tests if the current user is running as an administrator on this machine.

        .DESCRIPTION
        Tests if the current user is running as an administrator on this machine.

        .EXAMPLE
        Test-Administrator
    #>


    Write-Verbose -Message 'Testing for administrative rights.'
    $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
    $admin = [System.Security.Principal.WindowsBuiltInRole]::Administrator
    $IsAdmin = $principal.IsInRole($admin)
    return $IsAdmin
}