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

    .DESCRIPTION
    Update a credential entry to the MDSCredentials file. A dynamic parameter of 'Name' allows for tab completion of available credentials that may be updated. A credential prompt will open to accept the new username and password.

    .EXAMPLE
    Update-MDSCredential -Name MyCred1

    Update a credential entry named 'MyCred1'

    .NOTES

    #>

    [cmdletbinding()]
    Param ()

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

    Begin {}

    Process {
        Try {
            $Hash = Get-MDSCredential -SortByName:$false -ErrorAction Stop

            $Credentials = Get-Credential -ErrorAction Stop
            $Username = $Credentials.UserName
            $Password = $Credentials.Password | ConvertFrom-SecureString

            If ($Hash[$PSBoundParameters.Name]) {
                $Hash.Remove($PSBoundParameters.Name)
                $Hash.Add($PSBoundParameters.Name,@($UserName,$Password))
                $Hash | Export-CliXML $CredentialFilePath
                Write-Verbose "Updated credential record $($PSBoundParameters.Name)"
            }
            Else {
                $Message = "A record for {0} does not exist." -f $Object
                Write-Error -Message $Message -ErrorAction Stop -Exception ([System.Management.Automation.MethodInvocationException]::new())
            }
        }
        Catch {
            Write-Error $PSItem
        }
    }

    End {}
}