PSCreds.psm1

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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<#
    PowerShell Config and Credential Manager
 
    .SYNOPSIS
    Stores configuration and/or credentials for re-use with other PowerShell modules or scripts
 
    .DESCRIPTION
    Stores configuration and/or credentials for re-use with other PowerShell modules or scripts
 
#>


function New-Creds {
    <#
        .SYNOPSIS
        Securely stores a password in a local file
 
        .DESCRIPTION
        Securely stores a password cached in a local file. This file can only be decrypted on
        the same machine where this command was run.
 
        .PARAMETER Name
        The name of the file/service.
 
        .PARAMETER Path
        The path for the directory where the file will be stored. This should be specified
        without a trailing backslash.
 
        .EXAMPLE
        New-Creds -Name SMTP-Service -Path "C:\Scripts\Credentials"
    #>


    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [string]
        $Path
    )

    # If no path is specified then it stores the credential file in the user's %APPDATA%
    if (!$Path) {
        [string] $Path = [System.IO.Path]::Combine(
            [Environment]::GetFolderPath('LocalApplicationData'),
            "Microsoft",
            "PowerShellCredentials",
            "$Name"
        )
    }
    else {
        $Path = "$Path\$Name"
    }

    $null = New-Item -Path $Path -Force
    $Message = 'Please provide your key/password/token in the password field.'
    $Credential = Get-Credential -Message $Message
    $Credential | Export-CliXml -Path $Path
    Write-Output "Creating credential file in $Path..."

}

function Read-Creds {
    <#
        .SYNOPSIS
        Read in the credentials stored in a file.
 
        .DESCRIPTION
        Read in the credentials stored in a file.
 
        .PARAMETER Name
        The name of the file/service.
 
        .PARAMETER Path
        The folder where the credentials file is stored.
 
        .EXAMPLE
        Read-Creds -Path "C:\Scripts\Credentials\SMTP-Service.creds"
    #>

    [CmdletBinding()]
    param (

        [Parameter(Mandatory)]
        [string]
        $Name,

        [string]
        $Path
    )

    if (!$Path) {
        [string] $Path = [System.IO.Path]::Combine(
            [Environment]::GetFolderPath('LocalApplicationData'),
            "Microsoft",
            "PowerShellCredentials",
            "$Name"
        )
    }
    else {
        $Path = "$Path\$Name"
    }

    $Credential = Import-CliXml -Path $Path
    return $Credential
}