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
65
66
67
68
69
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
    }
}