CaiWuXiTong/scripts/install-upstream-tunnel-task.ps1

132 lines
4.6 KiB
PowerShell

#Requires -Version 5.1
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $ServerHost,
[ValidateRange(1, 65535)]
[int] $ServerPort = 22,
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string] $RemoteUser = 'caiwu-tunnel',
[Parameter(Mandatory = $true)]
[string] $PrivateKeyPath,
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $RemoteBindAddress,
[Parameter(Mandatory = $true)]
[ValidateRange(1, 65535)]
[int] $RemoteBindPort,
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $UpstreamHost,
[ValidateRange(1, 65535)]
[int] $UpstreamPort = 1433,
[ValidateRange(10, 300)]
[int] $RetrySeconds = 30,
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string] $TaskName = 'CaiWuXiTong-UpstreamTunnel'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function ConvertTo-TaskArgument {
param([Parameter(Mandatory = $true)][string] $Value)
return '"' + $Value.Replace('"', '\"') + '"'
}
$tunnelScript = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot 'keep-upstream-tunnel.ps1') -ErrorAction Stop).Path
$resolvedKeyPath = (Resolve-Path -LiteralPath $PrivateKeyPath -ErrorAction Stop).Path
$windowsPowerShell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
if (-not (Test-Path -LiteralPath $windowsPowerShell -PathType Leaf)) {
throw 'Windows PowerShell was not found; the tunnel task cannot be installed.'
}
$argumentList = @(
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-WindowStyle', 'Hidden',
'-File', (ConvertTo-TaskArgument $tunnelScript),
'-ServerHost', (ConvertTo-TaskArgument $ServerHost),
'-ServerPort', $ServerPort,
'-RemoteUser', (ConvertTo-TaskArgument $RemoteUser),
'-PrivateKeyPath', (ConvertTo-TaskArgument $resolvedKeyPath),
'-RemoteBindAddress', (ConvertTo-TaskArgument $RemoteBindAddress),
'-RemoteBindPort', $RemoteBindPort,
'-UpstreamHost', (ConvertTo-TaskArgument $UpstreamHost),
'-UpstreamPort', $UpstreamPort,
'-RetrySeconds', $RetrySeconds
)
$taskArguments = $argumentList -join ' '
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
if ($PSCmdlet.ShouldProcess($TaskName, 'register and start the read-only upstream tunnel task')) {
# The ScheduledTasks module can report false RPC errors on trimmed Windows
# installations. The built-in COM API works in Windows PowerShell and pwsh.
$taskService = New-Object -ComObject 'Schedule.Service'
$rootFolder = $null
$definition = $null
$registeredTask = $null
try {
$taskService.Connect()
$rootFolder = $taskService.GetFolder('\')
$definition = $taskService.NewTask(0)
$definition.RegistrationInfo.Description = 'CaiWuXiTong restricted read-only upstream tunnel with automatic reconnect.'
$definition.Principal.UserId = $currentUser
$definition.Principal.LogonType = 3 # TASK_LOGON_INTERACTIVE_TOKEN
$definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA
$definition.Settings.Enabled = $true
$definition.Settings.StartWhenAvailable = $true
$definition.Settings.DisallowStartIfOnBatteries = $false
$definition.Settings.StopIfGoingOnBatteries = $false
$definition.Settings.ExecutionTimeLimit = 'PT0S'
$definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW
$definition.Settings.RestartCount = 999
$definition.Settings.RestartInterval = 'PT1M'
$trigger = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON
$trigger.UserId = $currentUser
$trigger.Enabled = $true
$action = $definition.Actions.Create(0) # TASK_ACTION_EXEC
$action.Path = $windowsPowerShell
$action.Arguments = $taskArguments
$action.WorkingDirectory = $PSScriptRoot
$registeredTask = $rootFolder.RegisterTaskDefinition(
$TaskName,
$definition,
6, # TASK_CREATE_OR_UPDATE
$null,
$null,
3, # TASK_LOGON_INTERACTIVE_TOKEN
$null
)
$null = $registeredTask.Run($null)
Write-Output ('Scheduled task {0} was registered and started.' -f $TaskName)
}
finally {
foreach ($comObject in @($registeredTask, $definition, $rootFolder, $taskService)) {
if ($null -ne $comObject -and [System.Runtime.InteropServices.Marshal]::IsComObject($comObject)) {
[void] [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($comObject)
}
}
}
}