I'm trying to build a Powershell function that will create a Windows Scheduled Task on my onPrem server as part of my Azure release pipeline, which will need to run with the "Run whether user is logged on or not", so I am passing it an AD Service account UserID & Password.
This works totally fine if I use a plain text password from a variable, but I would like to import the password from my Azure KeyVault. I'll call it "PasswordFromKeyVault".
I have added a new Variable Group, linked to the Keyvault and it retrieves the value correctly.
Here is the Powershell script I am using in this step:
$TaskName = "HelloNewTaskWorld"
$Trigger= New-ScheduledTaskTrigger -At 10:02am -Daily
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PowershellScripts\Somescript.ps1"
$principal = New-ScheduledTaskPrincipal -UserId $(PlainTextUserIdVariable) -LogonType ServiceAccount
$description = "Testing AzureDevOps ability to deploy a fully configured scheduled task"
#As expected, outputs xxx to the console
Write-Host $(PasswordFromKeyVault)
Register-ScheduledTask -TaskName $TaskName -Description $description -Trigger $Trigger -Action $Action -Principal $principal –Force
Set-ScheduledTask -TaskName $TaskName -User $principal.UserID -Password $(PasswordFromKeyVault)
But when it runs, I receive the error message "The user name or password is incorrect":
2022-04-11T16:18:23.0724016Z Set-ScheduledTask : The user name or password is incorrect.
2022-04-11T16:18:23.0724884Z At C:\vstsagent\XW14Agent1\_work\_temp\90f67b9e-e6f7-4f71-9be9-fe24498f535e.ps1:16 char:1
2022-04-11T16:18:23.0725477Z + Set-ScheduledTask -TaskName $TaskName -User $principal.UserID -Passwo ...
2022-04-11T16:18:23.0726111Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2022-04-11T16:18:23.0726638Z + CategoryInfo : AuthenticationError: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Set-Scheduled
2022-04-11T16:18:23.0727110Z Task], CimException
2022-04-11T16:18:23.0727497Z + FullyQualifiedErrorId : HRESULT 0x8007052e,Set-ScheduledTask
I assume this is because the Azure Keyvault value is encrypted, and cannot be decrypted (which is exactly what I want), but does anyone know how I can create a credential using an already encrypted password?
$Password = "ABCDEF@1234" $passwordFromKeyVault = ConvertTo-SecureString -AsPlainText $Password -Force