CredDrive.class.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
#requires -module SHiPS
using namespace Microsoft.Powershell.SHiPS
using namespace CredentialManagement

[SHiPSProvider(UseCache = $true)]
class CredentialEntry : SHiPSLeaf {
    [string]$Target
    [string]$Description
    [string]$Username
    [CredentialType]$Type
    [PersistanceType]$Scope
    [datetime]$Modified
    [PSCredential]$Credential

    CredentialEntry([Credential]$Entry) : base($Entry.Target) {
        $this.Target = $Entry.Target
        $this.Description = $Entry.Description
        $this.Username = $Entry.Username
        $this.Type = $Entry.Type
        $this.Scope = $Entry.PersistanceType
        $this.Modified = $entry.LastWriteTime

        #Build a PSCredentialObject based on available information
        if ($Entry.Username -and $Entry.SecurePassword) {
            $this.Credential = [PSCredential]::New($Entry.Username, $Entry.SecurePassword)
        } elseif ($Entry.Username -and $Entry.Password) {
            $this.Credential = [PSCredential]::New($Entry.Username, (ConvertTo-SecureString -String $Entry.Password -AsPlainText -Force))
        } else {
            $this.Credential = [PSCredential]::Empty
        }
    }

    [PSCredential] GetContent() {
        return $this.Credential
    }
}

[SHiPSProvider(UseCache = $false)]
class CredentialManagerDrive : SHiPSDirectory {
    CredentialManagerDrive([string]$name) : base($name) {}

    [CredentialEntry[]] GetChildItem() {
        $filteredCredentialEntries = [CredentialSet]::New().Load().Where{$_.username -and ($_.password -or $_.SecurePassword) -and $_.type -in 'DomainPassword','Generic'}.where{$_.target -notmatch 'WindowsLive'}
        $credentialEntries = foreach ($credentialItem in $filteredCredentialEntries) {
            [CredentialEntry]::New($credentialItem)
        }
        return $credentialEntries
    }
}

[CredentialEntry]::new([Credential]::new()) | 
    Format-Table target,username,modified,Scope -Autosize | 
    ConvertTo-PSTypeFormat -TypeName 'CredentialEntry' -Path $PSScriptRoot/CredentialEntry.ps1xml -Force
Update-FormatData -PrependPath $PSScriptRoot/CredentialEntry.ps1xml