A cloud-based identity and access management service for securing user authentication and resource access
Could it be that you have not spesified user? Maby if you add:
$TaskPrincipal = New-ScheduledTaskPrincipal "$env:USERNAME"
or
$TaskPrincipal = New-ScheduledTaskPrincipal "System"
And add the -Principal to the register-scheduledtask command at the end?
Register-ScheduledTask -TaskName $taskName -InputObject -Principal $inputObject $TaskPrincipal
Take a look at this article...
https://www.patrickvanbemmelen.nl/set-a-powershell-script-or-other-file-as-scheduled-task-with-endpoint-manager/