Tuesday, April 17, 2018

Using Saved Credentials with PowerShell Scripts

Most of the time in a Windows environment, a Windows PowerShell script runs in the security context of the user account that is running it. If you have a scheduled task that runs a PowerShell script then you can specify a user account (service account) that is used to run the task. The service account needs to be assigned the necessary permissions to perform any actions in the script.

In some cases, you need to script to access remote resources and sign in. For example, if you have a scheduled task that pulls reporting information from Office 365. PowerShell has a method for storing encrypted credentials that can only be accessed the user account that stored them. The code below prompts you for a credential and then stored is encrypted in an XML file.

$credential = Get-Credential
$credential | Export-CliXml D:\credential.xml

To retrieve the credential and using it within a script, you read it from the XML file:

$credential = Import-CliXml D:\credential.xml

If you created the XML file while signed in as your account and then attempt to read it from a script running as a service account, it will fail because it can't be decrypted. Information in the correct user profile is required to decrypt the credential in the XML file. This also means that the encrypted file cannot be moved to another computer because the information required to decrypt the credential is not available on other computers.

To prepare a credential for use with a scheduled task, you can sign in as the service account to create it. This works if the service account has permission to sign in interactively or via remote desktop. However, I'm often in scenarios where I remote in to client sites as a specific user account and don't have the option to sign in directly as the service account.

If you can't sign in directly as the service account, you can spawn a new PowerShell prompt that runs as the service account and then create the XML file from the new PowerShell prompt. Use the following command to spawn a new PowerShell prompt and enter runas credentials:

Start-Process powershell.exe -Credential ""

Sign in as the service account when prompted with credentials. Then you can create an XML file with credentials that can be read by the service account when the script runs.

Note that in some cases, you need close your initial PowerShell prompt before you can enter commands in the new PowerShell prompt. This seems to vary by operating system and I've not mapped out the exact dependencies.


No comments:

Post a Comment