Skip to content

Instantly share code, notes, and snippets.

@marc-fez
Created October 29, 2014 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marc-fez/9591722e384f16376926 to your computer and use it in GitHub Desktop.
Save marc-fez/9591722e384f16376926 to your computer and use it in GitHub Desktop.
KPScript retrieve password in Powershell
function Get-KeepassPW{
$result = $null
$KeePath = "C:\Program Files (x86)\KeePass Password Safe 2\KPScript.exe"
# Path to your database
$KeeDataPath = "C:\Users\MyUser\Documents\KeePass\Database.kdbx"
while(!$result){
$pass = Read-Host 'What is your KeePassword?' -AsSecureString
$KePassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
$KeeCommands = @(
"-c:GetEntryString"
"""$KeeDataPath"""
"-pw:$KePassword"
"-Field:Password"
"-refx-UUID:B6881874DF188E4CB4201033EE2AAE51" # Best way I coud find to locate a KP entry, check properties of your entry
"-FailIfNotExists"
)
$result = & $KeePath $KeeCommands # $result will be an array, index[0] will either be your password or an error string
if(!$result -or $result[0] -match "^E: The composite key is invalid!$"){
$result = $null
write-host "Invalid Password or error retrieving password. Please try again."
}
}
return $result[0]
}
@marc-fez
Copy link
Author

Function that prompts the user for a keepass password and returns a specific password for the keepass database. I use this for a script that has a changing password I keep in KeePass. This way I can access the up to date password without having to remember or type it.

I had some problems with KeePass passwords that include spaces. If you can figure that out, cool. Also, the UUID was the only way I could determine to actually find the entry i was looking for.

Relies on KeePass and KPScript.

@hasafi
Copy link

hasafi commented Dec 7, 2020

hi @marc-fez,
you can use these fields:

$KeeCommands = @(	
	"-c:GetEntryString"
	"""$KeeDataPath"""
	"-pw:$KeePwd"
            "-Field:Password"
	"-ref-Title:$FQDN"
	"-ref-UserName:$user"
	"-FailIfNotExists"

)
so you don't need UUID but just hostname and user.
thanks for your example

@theolike
Copy link

theolike commented Feb 10, 2022

KPScript requires quotes around passwords with spaces, so you could use this:

"-pw:`"$KePassword`""

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment