Public/Remove-MDSCredential.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
Function Remove-MDSCredential {
    <#
    .SYNOPSIS
    Remove a credential entry to the MDSCredentials file

    .DESCRIPTION
    Remove a credential entry to the MDSCredentials file. Supply the name of the entry and be prompted for a username and password.

    .EXAMPLE
    Remove-MDSCredential -Name MyCred1

    Remove a credential entry named 'MyCred1'

    .NOTES

    #>

    [CmdletBinding(
        SupportsShouldProcess=$True,
        ConfirmImpact='High'
    )]
    Param ()

    DynamicParam {
        $Options = @(
        Get-MDSCredential -ErrorAction Stop |
                Select-Object -ExpandProperty Name
        )
        New-DynamicParam -Name Name -ValidateSet $Options -Position 0 -ParameterSetName Name
    }

    Begin {}
    Process {
        Try {
            # Get a hash table of the credential store
            $Hash = Get-MDSCredential -SortByName:$false -ErrorAction Stop

            $Name = $PSBoundParameters.Name
            # Confirm the removal name exists and remove it from the ash
            If ($Hash[$Name]) {
                If ($PSCmdlet.ShouldProcess($Name,"Remove credential record")) {
                    $Hash.Remove($Name)
                    Write-Verbose "Removed credential record $($Name)"
                }
            }
            Else {
                $Message = "A record for {0} does not exist." -f $Name
                Write-Error -Message $Message -ErrorAction Stop -Exception ([System.Management.Automation.MethodInvocationException]::new())
                Continue
            }

            # Update the store file
            Write-Verbose "Updating file $CredentialFilePath"
            $Hash | Export-CliXML $CredentialFilePath
        }
        Catch {
            Write-Error $PSItem
        }
    }
    End {}
}