Access Windows Task credentials in the PowerShell Script Access Windows Task credentials in the PowerShell Script powershell powershell

Access Windows Task credentials in the PowerShell Script


No, you can't have the script access the credentials you used in setting up the task.

However, you can store your credentials in a [PSCredential] object, then save that out to a file using Export-Clixml. When the script runs, import the credential with Import-Clixml.

The XML file will store the password encrypted, and it will only be able to be decrypted by the same user on the same computer (so you must store it as the user the task will be running as).

Example code for storing credential:

Get-Credential | Export-Clixml -Path C:\scripts\task\${env:USERNAME}_cred.xml

Example code for retrieving credential:

$cred = Import-Clixml -Path C:\scripts\task\${env:USERNAME}_cred.xml

Because the cred needs to be decrypted by the same user, I like to use the current user in the file name to be sure you're retrieving the correct file. It also helps in case you want to have multiple users run the script (you won't need different versions of it).

If you're using PowerShell cmdlets like Invoke-RestMethod or Invoke-WebRequest then it will take a -Credential parameter and you can pass the credential object directly.

If instead you need to build custom auth headers or send the credentials directly, then you need to get them from the object:

$user = $cred.Username$pass = $cred.GetNetworkCredential().Password

Note that $pass is not encrypted at this point, if you leave it in the credential object it's encrypted in memory.