'Add Windows Credentials using PowerShell & cmdkey
I am trying to use credentials from some UI prompted to add Windows credentials using cmdkey:
$sessionCredential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "Server Crdentials")
$ps = ConvertFrom-SecureString -SecureString $sessionCredential.password
cmdkey.exe /add:server1 /user:$($sessionCredential.UserName) /pass:$($ps)
The credentials are added correctly, but the password is not.
What can I do?
Solution 1:[1]
Apparently, the problem is ConvertFrom-SecureString is returning an encrypted standard string, ConvertFrom-SecureString.
And the option to get plain text is not available on PowerShell 5.1.
I found the correct convert here.
I understand it is not secured. It is used inside secured clients.
See fixed code below:
$sessionCredential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "Server Crdentials")
$mpass = [System.Net.NetworkCredential]::new("",$sessionCredential.password).Password
cmdkey.exe /add:server1 /user:$($sessionCredential.UserName) /pass:$($mpass)
Solution 2:[2]
Use the CredentialManager PowerShell module. It saves the password in the same place as cmdkey
, but it can take PSCredential objects directly without needing to convert to text.
Import-Module CredentialManager
# Get the credential from the user with a windows credentials prompt:
$SessionCredential = Get-Credential -Message 'Please enter your server credentials'
# Save the credential object directly without unwrapping it:
New-StoredCredential -Credentials $SessionCredential -Target ServerCredentials -Persist Enterprise `
-Comment "Server Credentials for $($SessionCredential.UserName)" > $null
# Open the credential later
$SavedCred = Get-StoredCredential -Target ServerCredentials
# Delete if needed
Remove-StoredCredential -Target ServerCredentials
cmdkey /pass:$($ps)
is prone to errors due to PowerShell garbling password characters.
Solution 3:[3]
Cpt.Whale's answer worked like a charm. The only caveat was the need to copy/distribute the CredentialManager module before using it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Mortensen |
Solution 2 | Peter Mortensen |
Solution 3 | Peter Mortensen |