Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Windows Task credentials in the PowerShell Script

I need to automate running a PowerShell script using Windows Task Scheduler. My problem is that in my PS script I need to send my credentials to a web service. I don't want to write my credentials in the file as it's plain text and easily accessible by others.

Can I have my script access the credentials I used in setting up the task?

like image 715
David Lozzi Avatar asked May 27 '15 20:05

David Lozzi


1 Answers

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.

like image 76
briantist Avatar answered Sep 23 '22 15:09

briantist