public/New-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
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
<#
    .Synopsis
        Create a PSCredential object.
    .Description
        Create a PSCredential object.
    .Example
        PS C:\> New-Credential -UserName 'user' -InsecurePassword 'My Password'
        Creates a PSCredential object from a plain text password.
    .Example
        PS C:\> New-Credential -UserName 'domain\user' -Password $mySecureStringPassword
        Creates a PSCredential object from a secure string password.
#>

function New-Credential {
    [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingUserNameAndPassWordParams', '')]
    [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingPlainTextForPassword', '')]
    [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingConvertToSecureStringWithPlainText', '')]
    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'Secure')]
    param (
        # The name of the user.
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Secure')]
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Insecure')]
        [String]
        $UserName,
        # The password as a SecureString.
        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'Secure')]
        [SecureString]
        $Password,
        # The password as an insecure String.
        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'Insecure')]
        [String]
        $InsecurePassword
    )

    begin {
        Write-LogMessage -Message "Started execution"
    }

    process {
        switch ($PSCmdlet.ParameterSetName) {
            'Secure' {
                $securePassword = $Password
            }
            'Insecure' {
                $securePassword = ConvertTo-SecureString -String $InsecurePassword -AsPlainText -Force
                Remove-Variable -Name 'InsecurePassword' -Force
            }
        }

        $parameters = @{
            TypeName     = 'System.Management.Automation.PSCredential'
            ArgumentList = @(
                $UserName,
                $securePassword
            )
        }

        if ($PSCmdlet.ShouldProcess("UserName: $UserName", "Create credential")) {
            return New-Object @parameters
        }
    }

    end {
        Write-LogMessage -Message "Finished execution"
    }
}