Save-Credential.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
<#
.Synopsis
    Saves a PSCredential object to the specified name.
 
.Description
    Saves a [PSCredential] object to the specified name and persists
    this information to the disk at $home\AppData\Low\SimplyCredential\.
 
.Parameter Name
    The reference name for the [PSCredential].
 
.Parameter Credential
    The [PSCredential] to persist.
 
.Parameter Force
    Use this to overwrite an existing saved credential.
#>

function Save-Credential {
    param([Parameter(Mandatory, ValueFromPipelineByPropertyName)][string]$Name
        , [Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline)][pscredential]$Credential
        , [switch]$Force)
    
    if($script:CredList.Keys -notcontains $name -or $Force) { 
        $script:CredList[$Name] = $Credential
        $script:CredList | Export-Clixml -Path $script:CredListPath -Force
    }
    else { throw "The credential '$name' already exists, use -Force to overwrite." }
}

Export-ModuleMember -Function Save-Credential