Get-KPEntry.ps1


# http://keepass.info/help/v2_dev/scr_sc_index.html#getentrystring
# http://it-by-doing.blogspot.com.br/2014/10/accessing-keepass-with-powershell.html
#.ExternalHelp psKeePass.Help.xml
function Get-KPEntry
{
    # http://technet.microsoft.com/en-us/library/hh847872.aspx
     [CmdletBinding(DefaultParameterSetName='Parameter Set 1', 
                  SupportsShouldProcess=$true, 
                  PositionalBinding=$false
                  #HelpUri = 'http://www.microsoft.com/',
                  #ConfirmImpact='Medium'
                  )]
     #[OutputType([String])]

    param(
            [Parameter(Mandatory=$False, Position = 1, HelpMessage="Use managedServer name.")]
                [string]$KeyPassFile,
            [Parameter(Mandatory=$False, HelpMessage="Use filter EntryKeys.", ParameterSetName='EntryKeys')]
                [EntryKeys[]]$Key,
            [Parameter(Mandatory=$False, HelpMessage="Use filter Value.", ParameterSetName='EntryKeys')]
                [string]$Value,
            [Parameter(Mandatory=$False)]
                [Security.SecureString]$MasterPassword=(Get-KPSecurityPassword -Alias Default).MasterPassword,
            [Parameter(Mandatory=$False, HelpMessage="Use managedServer name.")]
                [Switch]$ForcePlainText
    )

    BEGIN
    {
        $currentMethod = (Get-PSCallStack)[0].Command
        if (-not $MasterPassword)
        {
            do
            {
                $MasterPassword = Read-Host -Prompt "Type the Master Password to KeepPass Database `n$($KeyPassFile)" -AsSecureString
            }While(-not $MasterPassword)
        }

        New-KPParamHistory -Function $currentMethod -Parameter KeyPassFile -Content $KeyPassFile


        
        function Get-ProtectedString ($protectedStringDictionary)
        {
            foreach ($item in $protectedStringDictionary)
            {
                if ( ($item.Key -eq "Password") -and (-not $ForcePlainText.IsPresent) )
                {
                    $val = $protectedStringDictionary.Strings.ReadSafe($item.Key) | ConvertTo-SecureString -AsPlainText -Force
                }
                else
                {
                    $val = $protectedStringDictionary.Strings.ReadSafe($_.Key)
                }
                Add-Member -InputObject $entry -MemberType NoteProperty -Name $_.Key -Value $val
                return $entry
            }

        }                           

    }#BEGIN
    
    PROCESS
    {
        $kpDatabase = new-object KeePassLib.PwDatabase

        $compositeKey = new-object KeePassLib.Keys.CompositeKey
        #$m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpUserAccount))
        $compositeKey.AddUserKey((New-Object KeePassLib.Keys.KcpPassword($MasterPassword | ConvertTo-KPPlainText)));

        $iOConnectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
        $iOConnectionInfo.Path = $KeyPassFile

        $iStatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger

        try
        {
            $kpDatabase.Open($iOConnectionInfo,$compositeKey,$iStatusLogger)
        }
        catch [KeePassLib.Keys.InvalidCompositeKeyException]
        {
            Write-Host Incorrect password. $($_.Exception.Message) -ForegroundColor Red
            break;
        }
        catch [Exception]
        {
            $_.Exception.Message
            Write-KPLog -message $_ -Level EXCEPTION
            break;
        }
    
        $kpItems = $kpDatabase.RootGroup.GetObjects($true, $true)

        if (-not $key)
        {
            $Key = [System.Enum]::GetValues('EntryKeys')
        }
        if (-not $Value)
        {
            $Value = '*'
        }

        foreach($kpItem in $kpItems)
        {
            foreach ($k in $key)
            {
                $val = $kpItem.Strings.ReadSafe($K)

                if ( $val -and ($val -like $Value) )
                {
                    $entry = New-Object PSObject
                    $kpItem.Strings | % {
                                            if ( ($_.Key -eq "Password") -and (-not $ForcePlainText.IsPresent) )
                                            {
                                                try
                                                {
                                                    $val = $kpItem.Strings.ReadSafe($_.Key) | ConvertTo-SecureString -AsPlainText -Force -ErrorAction stop
                                                }
                                                catch [Exception]
                                                {
                                                    $val = $_.Exception.Message
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    $val = $kpItem.Strings.ReadSafe($_.Key)
                                                }
                                                catch [Exception]
                                                {
                                                    $val = $_.Exception.Message
                                                }

                                            }
                                            #Add-Member -InputObject $entry -MemberType NoteProperty -Name $_.Key -Value $val
                                            Add-Member -InputObject $kpItem -MemberType NoteProperty -Name $_.Key -Value $val
                                        }
                    #Write-Output $entry
                    Set-KPStandardMembers -MyObject $kpItem -DefaultProperties UserName,Password,Title,URL
                    Write-Output $kpItem
                    break;
                }#if
            }
        }
        #$kpDatabase.Close()


    }#PROCESS
    END
    {
        $kpDatabase.Close()
    }#END

}