private/Set-iPerf3Task.ps1

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
<#
    .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"
#>


function Set-iPerf3Task {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Port,
        [Switch]
        $PassThru
    )

    $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
    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 started.'
    }
    else {
        throw "Scheduled task for iPerf3 server was not registered. Message: $($error[0].Exception.message)"
    }

    if ($PassThru) {
        return $toReturn
    }
}