Stop Hardcoding Passwords in Scheduled PowerShell Scripts with SecretManagement and SecretStore
Move the password in a scheduled PowerShell script into a SecretStore vault owned by the task's account, unlock it unattended with a DPAPI-protected file, and test the task…

Move the password out of the script and into a SecretStore vault that belongs to the account the scheduled task runs as. Do the setup in that account’s own context, protect the vault’s password with a DPAPI-encrypted file only that account on that server can read, and have the script call Unlock-SecretStore and Get-Secret at the start of each run. Run the task once by hand, confirm it succeeded, and only then strip the plaintext copy from the script and change the password it exposed. One thing to know before you start: Microsoft now describes the SecretManagement and SecretStore modules as feature complete. They still get security and critical bug fixes, but no new development, so where the target system accepts a managed identity, a federated credential or a certificate, use that instead and keep this pattern for the passwords and API keys you cannot get rid of yet.
#The problem with a password in a scheduled script
Many Windows estates have a handful of scheduled PowerShell scripts that log in to something: a SQL login for a nightly report, an API key for a ticketing system, a service account for a file copy to a partner’s SFTP server. The quick way to write them was a literal string near the top of the file. That string is readable by anyone who can read the script, it travels into every backup and every copy someone takes to “just test something”, and it can end up in source control.
SecretManagement gives scripts one set of cmdlets (Set-Secret, Get-Secret, Get-SecretInfo, Remove-Secret) that work against whichever vault is registered. Microsoft’s overview lists the point of that abstraction: a script can be shared without knowing which vault each user has, and the backend can change without rewriting every script. SecretStore is Microsoft’s local vault for it. It stores secrets in a file for the current user and encrypts the file contents with .NET cryptographic APIs, on any platform that runs PowerShell 7.
The current releases are SecretManagement 1.1.2 and SecretStore 1.0.6. Both repositories are archived. That is not a reason to leave passwords in scripts, but it is a reason not to build anything new around the vault format, and to treat this as the tidy-up for credentials that are on their way out.
#How the pieces fit on one server
There are three layers, and each one is tied to a single Windows account on a single machine.
- The vault registration:
Register-SecretVaultadds the vault to the current user’s registry of vaults only. Other accounts on the server never see it, and the first vault registered becomes the default even without-DefaultVault. - The SecretStore itself. Its scope is always
CurrentUser;AllUsersis listed as an accepted value but is not supported. By default the store needs a password, prompts for it, and stays unlocked for 900 seconds after you supply it. - The vault password at rest. A scheduled task cannot type a password, so the vault is set to
Interaction Noneand the script unlocks it with a SecureString read from a file written byExport-Clixml. On Windows that file is encrypted with the Data Protection API, and Microsoft states that only your user account on only that computer can decrypt it.
So the whole design depends on one fact: every step runs as the task’s account. If you register the vault from your own admin session, the vault lands in your profile, the task’s account cannot find it, and the first run fails. Microsoft’s automation walkthrough says the setup commands must be run in the user context of the automation account on the host.
There is also an option to run SecretStore with Authentication None. The SecretStore README explains that the secrets are still encrypted, but the decryption key is stored in a file in the user’s own location, and the cmdlet reference warns that it is less secure and should not be used for important secrets. For a production credential, keep the password and protect it with DPAPI as below.

#Setting it up for the task’s account
Work on one task at a time. Before you change anything, note the task’s name and folder in Task Scheduler, the account it runs as, and the path of the script it calls. Copy the script to a folder only administrators can read, so you have the original to put back; that copy still contains the password, so delete it once the new version has run cleanly for a week or so.
- Open a PowerShell 7 session as the task’s account. From an elevated prompt run
runas /user:CONTOSO\svc-reports "pwsh.exe"and enter the account’s password when asked.runasloads the user’s profile by default, so everything you create in this window belongs to that account. It relies on the Secondary Logon service and on the account being allowed to log on to the computer, so check both if it fails. - Install and load the modules in that session.
1Install-Module -Name Microsoft.PowerShell.SecretStore -Repository PSGallery -Force 2Install-Module -Name Microsoft.PowerShell.SecretManagement -Repository PSGallery -Force 3Import-Module Microsoft.PowerShell.SecretStore 4Import-Module Microsoft.PowerShell.SecretManagement - Create the vault password and save it encrypted. Pick a long random password and keep a copy in your organisation’s password manager, because losing it means resetting the store.
1$credential = Get-Credential -UserName 'SecureStore' 2$securePasswordPath = 'C:\automation\passwd.xml' 3$credential.Password | Export-Clixml -Path $securePasswordPathThe user name is ignored; only the password is kept.
- Register the vault and set it to run without prompts.
1Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault 2$password = Import-Clixml -Path $securePasswordPath 3$storeConfiguration = @{ 4 Authentication = 'Password' 5 PasswordTimeout = 3600 6 Interaction = 'None' 7 Password = $password 8 Confirm = $false 9} 10Set-SecretStoreConfiguration @storeConfigurationPasswordTimeoutis in seconds. An hour suits a job that finishes in minutes; set it a little longer than your longest run. - Store the credential the script uses.
-NoClobbermakes the command fail rather than overwrite a secret that already has this name. SecretStore treats names as case-insensitive, soreportjob-sqlandReportJob-Sqlare the same secret.1$sqlLogin = Get-Credential -UserName 'report_reader' 2Set-Secret -Name 'ReportJob-Sql' -Secret $sqlLogin -Vault SecretStore -NoClobberA secret can be a
String,SecureString,PSCredential,Hashtableorbyte[]. You can add-Metadatasuch as an expiry date, but metadata is not stored securely, so never put anything sensitive in it. - Change the top of the script. Replace the hardcoded value with an unlock and a lookup, and leave the rest of the script alone:
1$securePasswordPath = 'C:\automation\passwd.xml' 2$password = Import-Clixml -Path $securePasswordPath 3Unlock-SecretStore -Password $password 4$sqlLogin = Get-Secret -Name 'ReportJob-Sql' -Vault SecretStore -ErrorAction StopNaming the vault with
-VaultstopsGet-Secretfrom searching other registered vaults and returning the first match it finds. Keep the old line commented out for now, not deleted, so the comparison in the next step is straightforward.
If the script only needs the password as text for a connection string, Get-Secret -AsPlainText returns it, but Microsoft’s own caution applies: avoid plaintext strings wherever you can, and never write the value to a log or transcript.
#Check it worked before you delete anything
Still in the runas session, prove each layer separately before you involve Task Scheduler.
Get-SecretStoreConfigurationshould showCurrentUser,Password, your timeout andNone.Test-SecretVault -Name SecretStoreruns the vault’s self-test and returnsTruewhen every test passes.Get-SecretInfo -Vault SecretStoreshould listReportJob-Sqlwith the typePSCredential. It shows names and types without revealing values.
Then close the session and run the real task from an administrator prompt with Start-ScheduledTask -TaskName 'Nightly report' -TaskPath '\Reports\'. It starts asynchronously, so wait for the job to finish and read the result with Get-ScheduledTaskInfo -TaskName 'Nightly report' -TaskPath '\Reports\', which returns the task’s last run-time information. Compare the run’s output with a normal night: the same report, the same row counts, the same file in the same place. A task that reports success but wrote nothing can mean the script carried on past an error, which is why the lookup uses -ErrorAction Stop.
Only when the scheduled run succeeds do you remove the commented-out password line. After that, change the password on the system it belongs to, because it has been sitting in plaintext and you cannot know every copy that was taken. Store the new one with Set-Secret without -NoClobber, which overwrites the existing secret, and run the task once more.
#What goes wrong when the task runs unattended
- “A valid password is required to access the Microsoft.PowerShell.SecretStore vault.” The vault is locked. Either the script never called
Unlock-SecretStore, or the run outlasted the timeout. WithInteraction None, a locked store throwsMicrosoft.PowerShell.SecretStore.PasswordRequiredExceptioninstead of waiting for a prompt. For a long run, pass a larger-PasswordTimeouttoUnlock-SecretStore, which overrides the configured value for that session. - The secret “wasn’t found”. Most often the vault was registered by a different account, usually the administrator who did the setup. Run
Get-SecretVaultas the task’s account; if it returns nothing, repeat the setup in that account’s context. Import-Clixmlfails to decrypt the password file. DPAPI ties the file to one user on one computer. A file copied from another server, or written by another account, cannot be read. Recreate it on the server, as the task’s account.- The task was moved to a Linux host.
Export-Clixmlonly encrypts on Windows. On Linux and macOS it writes the password as a Unicode character array, which is encoded, not encrypted. Microsoft’s walkthrough calls the file approach a Windows-only solution and suggests a secure variable from the CI system instead. - Someone ran
Set-SecretStorePasswordor reset the store. The saved file then holds the old password.Reset-SecretStoredeletes every secret in the store and is meant only for a lost password or corrupt files, so it should never be part of routine work.

#Permissions on the vault password file
DPAPI stops other accounts from decrypting passwd.xml, but anything that can run code as the task’s account can read it, unlock the vault and take every secret inside. That makes the service account the real boundary, so keep it narrow:
- One account per job, or per small group of related jobs, so one vault does not hold the keys to everything.
- No interactive logon rights beyond what the setup needs, and no membership of local Administrators unless the job really requires it.
- The script folder writable only by administrators. If the task’s account can edit its own script, anyone who compromises the account can change what the script does with the secret.
- The credential in the vault should have the least access the job needs: a read-only SQL login for a report, not
sa.
If you have certificate-based jobs in the same estate, the guide to finding expiring certificates on Windows Servers with PowerShell is a useful companion, since those jobs fail in a similar quiet way when a credential lapses. PowerShell 7.6 LTS also has a published end-of-support date, so plan the module install into whichever PowerShell 7 release you move to next.
#Backing out to the old script
Every change above can be undone in order, and none of them touches the system the credential logs in to until you rotate the password.
- Copy the original script back from the administrators-only folder and run the task once with
Start-ScheduledTaskto confirm it works as before. - As the task’s account, remove the stored credential with
Remove-Secret -Name 'ReportJob-Sql' -Vault SecretStore. Both the name and the vault must be given. - If nothing else uses the vault, run
Unregister-SecretVault -Name SecretStoreand deleteC:\automation\passwd.xml. Unregistering removes the vault from the account’s registry; registering it again under any name makes the stored secrets available again.
If you already rotated the password before backing out, the restored script holds the old one and will fail. Put the new password in the restored script only as a short-term measure, and plan the move again.
#Before you call the job done
The task has run on schedule at least once with the new script. Get-SecretInfo as the task’s account lists only the secrets that job needs. The vault password is in your password manager as well as in the DPAPI file. The old password has been changed on the target system, and the backup copy of the original script has been deleted. Then pick the next script on the list, and for each one ask first whether the system behind it can take a managed identity or a certificate instead, because Microsoft’s own direction for these modules is away from stored passwords altogether.
About this page
Credited to
Dates
Published
Sources
Corrections
No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.
Discover more
Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
Engineering insights, direct to you.
Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.
Comments
Add a thoughtful note on Stop Hardcoding Passwords in Scheduled PowerShell Scripts with SecretManagement and SecretStore. Comments are checked for spam and held for moderation before appearing.