Get-KPEntry.ps1

#.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, HelpMessage="Use to filter by GroupPath.")]
                [string]$GroupPath,
            [Parameter(Mandatory=$False, HelpMessage="Use KeePassLib.PwUuid object.", ParameterSetName='Uuid')]
                [KeePassLib.PwUuid]$Uuid,
            [Parameter(Mandatory=$False)]
                [Security.SecureString]$MasterPassword=(Get-KPSecurePassword -Alias Default).MasterPassword,
            [Parameter(Mandatory=$False, HelpMessage="Use managedServer name.")]
                [Switch]$ForcePlainText,
            [Parameter(Mandatory=$False, HelpMessage="Use managedServer name.")]
                [Switch]$IncludeRecycleBin,
            [Parameter(Mandatory=$False,DontShow)]
                [KeePassLib.Keys.CompositeKey]$CompositeKey,
            [Parameter(Mandatory=$False,DontShow)]
                [KeePassLib.Serialization.IOConnectionInfo]$ConnectionInfo
    )

    BEGIN
    {
        # 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
        $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)
        }

        $kpDatabase = new-object KeePassLib.PwDatabase
        $statusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger

        if (-not $CompositeKey)
        {
            $compositeKey = new-object KeePassLib.Keys.CompositeKey
            #$m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpUserAccount))
            $compositeKey.AddUserKey((New-Object KeePassLib.Keys.KcpPassword($MasterPassword | ConvertTo-KPPlainText)));
        }
        
        if (-not $ConnectionInfo)
        {
            if (Test-Path $KeyPassFile)
            {
                $connectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
                $connectionInfo.Path = $KeyPassFile
                New-KPParamHistory -Function $currentMethod -Parameter KeyPassFile -Content $KeyPassFile
            }
            else
            {
                Write-Host File $KeyPassFile not found. -ForegroundColor Red
                break;
            }
        }

        try
        {
            $kpDatabase.Open($connectionInfo,$compositeKey,$statusLogger)
            if ($Uuid)
            {
                $kpItems = $kpDatabase.RootGroup.FindEntry($Uuid,$true)
            }
            else
            {
                $kpItems = $kpDatabase.RootGroup.GetObjects($true, $true)
                if (-not $IncludeRecycleBin.IsPresent)
                {
                    $kpItems = $kpItems | ? {$_.ParentGroup.Uuid -ne $kpDatabase.RecycleBinUuid}
                }

            }
        }
        catch [KeePassLib.Keys.InvalidCompositeKeyException]
        {
            Write-Host Incorrect password. $($_.Exception.Message) -ForegroundColor Red
            break;
        }
        catch [Exception]
        {
            Write-Host $_.Exception.Message -ForegroundColor Red
            Write-KPLog -message $_ -Level EXCEPTION
            break;
        }

        try
        {
            $kpDatabase.Close()
        }
        catch [Exception]
        {
            Write-Host $_.Exception.Message -ForegroundColor Red
            Write-KPLog -message $_ -Level EXCEPTION
        }


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

        function Get-ParentGroup ($item)
        {
            if ($item)
            {
                try
                {
                    $item = $item.ParentGroup
                    [String]$pGroup = $null
                    While($item)
                    {
                        $pGroup = "\$($item.Name)" + $pGroup
                        $item = $item.ParentGroup
                    }
                    return $pGroup.ToString()
                }
                catch [Exception]
                {
                    return $null
                }
            }
        }

               

    }#BEGIN
    
    PROCESS
    {
        # GroupPath option
        if ($kpItems)
        {
            $kpItems | % {
                $gPath = Get-ParentGroup $_
                try
                {
                    Add-Member -InputObject $_ -MemberType NoteProperty -Name GroupPath -Value $gPath
                }
                catch [Exception]
                {
                    Write-KPLog -message $_ -Level EXCEPTION
                }
            }

            if ($GroupPath)
            {
                $kpItems = $kpItems | ? {$_.GroupPath -like $GroupPath}
            }
        }


        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") )
                                            {
                                                try
                                                {
                                                    $secPassword = $null
                                                    $secPassword = $kpItem.Strings.ReadSafe($_.Key) | ConvertTo-SecureString -AsPlainText -Force -ErrorAction stop
                                                    if ($ForcePlainText.IsPresent)
                                                    {
                                                        $val = $kpItem.Strings.ReadSafe($_.Key)
                                                    }
                                                    else
                                                    {
                                                        $val = $secPassword
                                                    }
                                                }
                                                catch [Exception]
                                                {
                                                    $val = $_.Exception.Message
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    $val = $kpItem.Strings.ReadSafe($_.Key)
                                                }
                                                catch [Exception]
                                                {
                                                    $val = $_.Exception.Message
                                                }

                                            }
                                            try
                                            {
                                                Add-Member -InputObject $kpItem -MemberType NoteProperty -Name $_.Key -Value $val
                                            }
                                            catch [exception]
                                            {
                                                Write-KPLog -message $_ -Level EXCEPTION
                                            }
                                            
                                        }
                    try
                    {
                        if ($kpItem.UserName -and $secPassword)
                        {
                            $psCred = New-Object System.Management.Automation.PSCredential ($kpItem.UserName, $secPassword)
                            Add-Member -InputObject $kpItem -MemberType NoteProperty -Name PsCredential -Value $psCred
                        }
                        #Add-Member -InputObject $kpItem -MemberType NoteProperty -Name GroupPath -Value (Get-ParentGroup $kpItem)
                        Add-Member -InputObject $kpItem -MemberType NoteProperty -Name compositeKey -Value $compositeKey
                        Add-Member -InputObject $kpItem -MemberType NoteProperty -Name connectionInfo -Value $connectionInfo
                        
                        Set-KPStandardMembers -MyObject $kpItem -DefaultProperties UserName,Password,Title,GroupPath
                    }
                    catch [Exception]
                    {
                        Write-KPLog -message $_ -Level EXCEPTION
                    }
                    Write-Output $kpItem
                    break;
                }#if
            }
        } 
        
    }#PROCESS
    END
    {}#END

}