PSSpeedTest.psm1

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
}