2,187
edits
(Initial creation - content from depreciated PowerShell page) |
(→Store Password Securely: Added "Convert SecureString To Plain Text") |
||
(2 intermediate revisions by the same user not shown) | |||
Line 44: | Line 44: | ||
</source> | </source> | ||
For a complete, but simple user/pass caching system use something like the following. | For a complete, but simple user/pass caching system use something like the following. I use this script to create a local user/pass file which gets used whenever I need to provide credentials in a script. | ||
<source lang="powershell"> | <source lang="powershell"> | ||
$UserFile = "User.fil" | |||
$PassFile = "Pass.fil" | |||
# Check for credential files, create if required | # Check for credential files, create if required | ||
if (!(Test-Path $UserFile) -or !(Test-Path $PassFile)) { | if (!(Test-Path $UserFile) -or !(Test-Path $PassFile)) { | ||
Line 61: | Line 64: | ||
</source> | </source> | ||
...obviously to make the above more useful you'd test that the user/pass combo supplied was correct prior to saving to file. | ...obviously to make the above more useful you'd test that the user/pass combo supplied was correct prior to saving to file. | ||
=== ConvertTo-SecureString : Key not valid for use in specified state === | |||
This is the error you get if you try to decrypt the contents of your password file using a user account other than that which was used to encrypt it. | |||
The password file must be created/encrypted as the same logged in user as the account under which the script will run. Therefore if your script will be running from a scheduled task, run from a server using a service account, you must be logged onto the that machine with the service account when you create the file. | |||
=== Convert SecureString To Plain Text === | |||
To decrypt a secure string use the following (this must be run from the same user session used to encrypt the string) | |||
<source lang="powershell"> | |||
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EncryptPass) | |||
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) | |||
</source> | |||
== Logged-In User's Credentials == | == Logged-In User's Credentials == |