Goal of the program: Run (.bat) file that disconnects Tailscale when the computer is idle for over 1 minute.
Here’s what I already have set up:
- A (.bat) file that disconnects tailscale.
@echo off
"C:Program FilesTailscaletailscale.exe" logout
- A powershell script (.ps1) that creates a task to deal with my conditions.
# Temporarily bypass execution policy
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force
# Get the script's directory
$scriptPath = $MyInvocation.MyCommand.Path
$scriptDir = Split-Path -Parent $scriptPath
# Path to the Tailscale executable
$tailscalePath = "C:Program FilesTailscaletailscale.exe"
# Debugging output
Write-Host "Script Path: $scriptPath"
Write-Host "Script Directory: $scriptDir"
Write-Host "Tailscale Path: $tailscalePath"
# Create the scheduled task using schtasks.exe with quoted paths
$taskName = "DisconnectTailscaleAfterIdle"
$action = "$tailscalePath logout"
$trigger = "ONIDLE"
$idleDuration = "1"
$runLevel = "HIGHEST"
$user = "SYSTEM"
# Build the schtasks command
$cmdArgs = @(
"/Create",
"/TN", "`"$taskName`"",
"/TR", "`"$action`"",
"/SC", "$trigger",
"/I", "$idleDuration",
"/F",
"/RL", "$runLevel",
"/RU", "$user"
)
# Execute schtasks command
$cmd = "schtasks.exe"
$process = Start-Process -FilePath $cmd -ArgumentList $cmdArgs -NoNewWindow -Wait -PassThru
if ($process.ExitCode -eq 0) {
Write-Host "Task created successfully."
} else {
Write-Host "Failed to create task. Exit code: $($process.ExitCode)"
# Capture the error output from schtasks
$errorOutput = $process | Select-Object -ExpandProperty StandardError
Write-Host "Error Output: $errorOutput"
}
- The latest installation of Inno Setup Compiler to compile all of this into a simple (.exe) to automate all of this for other users. Here is my (.iss) to compile these two scripts:
[Setup]
AppName=Tailscale Auto Disconnect
AppVersion=1.0
DefaultDirName={pf}TailscaleAutoDisconnect
OutputDir=.
OutputBaseFilename=TailscaleAutoDisconnectSetup
[Files]
Source: "CreateTaskAlt.ps1"; DestDir: "{app}Scripts"
[Run]
Filename: "powershell.exe"; Parameters: "-ExecutionPolicy Bypass -File ""{app}ScriptsCreateTaskAlt.ps1"""; Flags: runhidden
Upon compiling, the executable is created and installed to the default location (Program Files x86). The task is successfully created – as seen in Task Scheduler – but upon manually running the task, I get the following Last Run Result:
The system cannot find the file specified. (0x80070002)
Why? Everything in my code is right? Right??
Vividlee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
8