Task Scheduler with GMSA account

I am trying to change some Task Schedules and use GMSA account instead but at the same time remaining the use of Run weather user is logged on or not and highest privileges.I have this but it changes status of Run weather user is logged on or not to Run only when user is logged on.

## changeTaskUserName.ps1
## Author: Thomas Sköld
## Created: 2024-10-01
## Ver. 1.0 
## -----------------------------
# Hämta alla schemalagda uppgifter där användaren är 'Test123' och sökvägen innehåller 'One', 'Two' eller Three

$tasks = Get-ScheduledTask | Where-Object {
    ($_.Principal.UserId -eq 'test123') -and
    ($_.TaskPath -like "*One*" -or $_.TaskPath -like "*Two*" -or $_.TaskPath -like "*Three*")
}

# GMSA användare
$gmsaUserID = New-ScheduledTaskPrincipal -UserID "contoso\gMSA1234$" -LogonType Password -RunLevel Highest

# Uppdatera varje uppgift

foreach ($task in $tasks) {
    $taskName = $task.TaskName
    $taskPath = $task.TaskPath

# Sätt ny användare
    Set-ScheduledTask -TaskName $taskName -TaskPath $taskPath -Principal $gmsaUserID
}
Write-Host "Alla uppgifter med sökvägar 'One' eller 'Two' som kördes av 'Test123' har nu ändrats till 'contoso\gMSA1234$'."

Are you starting the shell that runs this script using “Run as administrator”?

Yes I am and that works fine. The problem appears when I am changing to gmsa account