I'm working on a PowerShell script that needs to run under a Group Managed Service Account (GMSA), but I've hit a snag. The script works just fine when run under my normal user account, but it seems the GMSA can't access the credential file created by my user account, likely due to permission issues. I need to find a way to create the credential file while logged in as the GMSA, but I can't interactively input anything for that account. Currently, I use the following command to create the credential file:
read-host -assecurestring "pass" | convertfrom-securestring | out-file C:powershell_scriptscred.txt
Does anyone have suggestions on how to solve this problem?
4 Answers
Honestly, it's worth considering if you really need to store the credentials this way. If your script is running under the GMSA account, it should already have the necessary access to whatever resources it needs without having to pass the credentials. That could simplify your approach a lot!
You might also try using the `-Key` parameter with functions that work with SecureString. This lets you specify a 16-byte initialization vector. That way, you can store and recover the SecureString across different user contexts. Just remember that the key needs to be handled carefully, like a password!
An alternative approach is to use `Protect-CMSMessage` to securely manage the passwords. You could create a certificate during the script run and then encrypt your password with that certificate, which only the GMSA can access. Here’s a simple framework you can follow:
$cert = Get-ChildItem cert:CurrentUserMy | ? {$_.EnhancedKeyUsageList.FriendlyName -contains 'Document Encryption'} | ? hasprivatekey -eq $true | ? notafter -gt (date)
if (-not $cert) {
$cert = New-SelfSignedCertificate -DnsName $env:username -CertStoreLocation "Cert:CurrentUserMy" -KeyUsage KeyEncipherment,DataEncipherment,KeyAgreement -Type DocumentEncryptionCert
}
Then you can encrypt the password with the generated certificate and use `Unprotect-CMSMessage` to retrieve it when needed!
The issue here isn't just about permissions; it centers around how DPAPI encryption works. This uses both a user key and a computer key, so a different user, like the GMSA, can't decrypt a password encoded with your personal key. A potential solution is to set up a scheduled task to update the password instead. You could save the current password in a simple text file and run a task to convert it into a SecureString and save it where the GMSA can access it. Here's a quick example:
$passwordFile = 'C:temppassword.txt'
Get-Content $passwordFile |
ConvertTo-SecureString -AsPlainText -Force |
Out-File C:powershell_scriptscred.txt
Remove-Item $passwordFile
Just make sure you clean up the password file afterwards!

Just keep in mind that users on the machine will require access to the private key to decrypt the message, which might be tricky since non-admins usually can't do that.