src/Get-CsEntry.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
<#
.SYNOPSIS
    Get CredentialStore Entries
.DESCRIPTION
    The Get-CsEntry cmdlet gets objects that represent the CredentialStore entries for a file.
.PARAMETER FilePath
    Specifies the path to the CredentialStore file.
.PARAMETER Name
    Specifies the CredentialStore entries names of entries to be retrieved. Wildcards are permitted. By default,
    this cmdlet gets all of the entries in the CredentialStore file.
.Example
    Get-CsEntry -FilePath CredentialStore.json
    This command gets all CredentialStore entries in the CredentialStore.json file.
.Example
    Get-CsEntry -FilePath CredentialStore.json -Name "LocalServer"
    This command retrieves CredentialStore entry with the name LocalServer.
.Example
    Get-CsEntry -FilePath CredentialStore.json -Name "vmm*"
    This command retrieves CredentialStore entries with names that begin with vmm.
.LINK
    https://github.com/fodonnel/CredentialStore
#>

function Get-CsEntry {
    [CmdletBinding()]
    param(
        [ValidateScript( {
                if (Test-Path $_) { $true }
                else { throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' does not exist." }
            })]
        [Parameter(Mandatory = $false, Position = 0)]
        [Alias("File")]
        [string] $FilePath = (Get-CsDefaultStore),

        [Parameter(Mandatory = $false)]
        [string[]] $Name = "*"
    )

    $store = Get-Content -Raw -Path $FilePath | ConvertFrom-Json
    if ($store.Username -ne $(whoami) -or $store.ComputerName -ne $(hostname)) {
        throw "Cannot access CredentialStore, it is encrypted for user $($store.UserName) on Computer $($store.ComputerName)"
    }

    $entries = @(foreach ($entry in $store.credentials) {
            if ( $Name | Where-Object { $entry.Name -like $_ }) {
                $entry
            }
        })

    foreach ($entry in $entries) {
        $password = ($entry.password | ConvertTo-SecureString)
        $cred = New-Object PSCredential($entry.username, $password)

        [PsCustomObject]@{
            Name        = $entry.Name
            Description = $entry.Description
            Credential  = $cred
        }
    }
}