Functions/Set-CredFile.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
Function Set-CredFile {

    <#
        .SYNOPSIS
            Stores credential into an xml file
        .EXAMPLE
            Set-CredFile
        .EXAMPLE
            Set-CredFile -Username admin -Path c:\temp\admin-cred.xml
        .EXAMPLE
            Set-CredFile -Force
        .LINK
            https://github.com/jorioux/F5-LTM-Helper
    #>


    param(
        [Parameter(Mandatory = $false)]
        [string]$Path=$([system.io.path]::GetTempPath()+"f5-cred.xml"),
        [string]$Username,
        [string]$Password,
        [switch]$Force
    )

    if($VerbosePreference -ne "SilentlyContinue"){
        $Verbose = $true
    } else {
        $Verbose = $false
    }

    Write-Verbose "Using cred file: $Path"

    #If username and password specified at arguments
    if(! ([string]::IsNullOrEmpty($Username))){
        Write-Verbose "Using username: $Username"
        if([string]::IsNullOrEmpty($Password)){
            $Password = Read-Host -AsSecureString "Password"
        }
        $secureStringPwd = $Password | ConvertTo-SecureString -AsPlainText -Force 
        $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $secureStringPwd
        $Cred | Export-CliXml -Path $Path -Verbose:$Verbose
        Write-Verbose "Exported credential to $Path"
        return $Cred
    }

    #Try to import the credentials from xml file
    $Cred = $null
    if(!($Force)){
        try{
            $Cred = Import-CliXml -Path $Path -Verbose:$Verbose
            Write-Verbose "`tSuccessfully imported credential (Username: $($Cred.UserName))"
        }catch{
            Write-Warning "`tUnable to import credential"
        }
    }

    #If unable to import existing creds, we create new one
    if($Cred -eq $null){
        Write-Verbose "Creating credential file..."
        try {
            $Cred = Get-Credential
        } catch {
            Write-Warning "`tFailed to create credential file"
            return $Cred
        }
        if($Cred -eq $null){
            Write-Warning "`tFailed to create credential file"
        } else {
            $Cred | Export-CliXml -Path $Path -Verbose:$Verbose
            Write-Verbose "`tExported cred file to $Path"
        }
    }

    return $Cred
}