You can have this done by enabling this two flags in your self-hosted agent command/script.
- --runAsService: Configures the agent to run as a service.
- --runAsAutoLogon: runs the agent each time after restarting the machine.
In one of my previous project. Here is the script I built specifically for this purpose.
# Define variables
$AgentPackageUrl = "https://vstsagentpackage.azureedge.net/agent/3.238.0/vsts-agent-win-x64-3.238.0.zip"
$AgentPackagePath = "$env:TEMP\agent.zip"
$AgentExtractPath = "C:\agent"
# Set Azure DevOps organization URL
$OrganizationUrl = "https://dev.azure.com/dammyboss"
# Set Personal Access Token
$PAT = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Set agent name
$AgentName = "xxx"
# Set pool name
$PoolName = "xxxxxx"
# Download agent package
Invoke-WebRequest -Uri $AgentPackageUrl -OutFile $AgentPackagePath
# Extract agent package
Expand-Archive -Path $AgentPackagePath -DestinationPath $AgentExtractPath
# Navigate to agent directory
Set-Location -Path $AgentExtractPath
# Run configuration script with parameters
& .\config.cmd --url $OrganizationUrl --token $PAT --pool $PoolName --agent $AgentName --unattended
In this script, I have added the necessary flags to run as a service and restart at logon. You would not have to worry about having to log in to the machine to start the agent.
I took the liberty to test this on one of my VMs just a few mins ago, see the result below. I restarted it and confirmed the service start running post restart.