Public/Get-LPCredential.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<#
.Synopsis
   Returns a PSCredential object for a URL
.DESCRIPTION
   Performs a regular expression match on a URL to create strings for various
   fuzzy matching scenarios, then returns an array of PSCredential objects
   that match the given URL. Optionally return only one entry.
.EXAMPLE
   Get-LPCredential
#>

function Get-LPCredential
{
    [CmdletBinding(PositionalBinding=$true,
                    DefaultParameterSetName='URL',
                    ConfirmImpact='Low')]
    [Alias("lastpass")]
    Param
    (
        # URL to find a credential for
        [Parameter(Mandatory=$true,
                    ParameterSetName='URL',
                    Position=0,
                    ValueFromPipelineByPropertyName=$true,
                    ValueFromPipeline=$true)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [String]
        $URL,

        # Only return the first result
        [Parameter()]
        [switch]
        $First,

        # Force a refresh
        [Parameter()]
        [Switch]
        $Refresh
    )

    Begin
    {
        if (!$LPVault)
        {
            $LPVault = Get-LPVault
        }
        if (!$LPKeys)
        {
            $LPKeys = Get-LPKeys
        }
        if (!$LPAccounts -or $Refresh)
        {
            $LPAccounts = Get-LPAccounts -Refresh:$Refresh
        }
    }
    Process
    {
        if (!($URL -match '(((((?:\w+\:\/\/)?(((?:\d{1,3}\.){3}\d{1,3})|(?:\w+\.)*((?:\w+\.)(?:\w+))|\w+))(?:\:\d+)?)(?:\/[^\?\.]*)*(?:\/)?(?:[-\w\.]*)?)(?:\??[^\/]*)?)?'))
        {
            throw "Bad URL format"
        }

        Write-Verbose "Searching through $($LPAccounts.Count) accounts"
        foreach ($match in $matches.GetEnumerator()) {
            Write-Verbose "Searching for: $($match.Value)"
            $Candidates = @($LPAccounts | Where-Object PSCredential -NE $null | Where-Object {$_.URL -like "*$($match.Value)" -or $_.URL -like "*$($match.Value)/*" -or $_.URL -like "*$($match.Value):*"})
            Write-Verbose "Found $($Candidates.Count) candidates"
            if ($Candidates.Count -gt 0)
            {
                if ($First)
                {
                    return $($Candidates.PSCredential | Select-Object -First 1)
                }
                else
                {
                    return $Candidates.PSCredential
                }
            }
        }

        throw "No matches found in LastPass vault"

    }
}