Scripts/New-BPACredentialStoreItem.ps1

function New-BPACredentialStoreItem {
    <#
        .SYNOPSIS
            Saves credentials for the specified BPA server
 
        .DESCRIPTION
            New-BPACredentialStoreItem stores a server and credential object together in a credential store file.
 
        .PARAMETER BPAServer
            The AutoMate BPA management server.
 
        .PARAMETER Credential
            The credentials use during authentication.
 
        .PARAMETER UserName
            The username to use during authentication.
 
        .PARAMETER Password
            The password to use during authentication.
 
        .PARAMETER FilePath
            The file to store the server/credential combinations in. It is stored in the user profile by default.
 
        .EXAMPLE
            New-BPACredentialStoreItem -BPAServer server01 -Credential (Get-Credential)
 
        .NOTES
            Author(s): : David Seibel
            Contributor(s) :
            Date Created : 05/04/2017
            Date Modified : 04/27/2018
 
        .LINK
            https://github.com/davidseibel/PoshBPA
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$BPAServer,        

        [Parameter(ParameterSetName = "ByCredential")]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.PSCredential]$Credential,

        [Parameter(ParameterSetName = "ByUserPass")]
        [ValidateNotNullOrEmpty()]
        [string]$UserName,

        [Parameter(ParameterSetName = "ByUserPass")]
        [ValidateNotNullOrEmpty()]
        [Security.SecureString]$Password,

        [string]$FilePath = "$($env:APPDATA)\PoshBPA\credstore.xml"
    )    

    if ($PSCmdlet.ParameterSetName -eq "ByUserPass") {
        $Credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
    }
    
    if (Test-Path -Path $FilePath) {
        $Items = Import-Clixml -Path $FilePath
        # Change it if it already exists, otherwise add it
        if ($Items -ne $null) {
            if ($Items[$BPAServer]) {
                $Items[$BPAServer] = $Credential
            } else {
                $Items.Add($BPAServer, $Credential)
            }
        } else {
            $Items = @{ $BPAServer = $Credential }
        }
    } else {
        # Create folder if it doesn't exist
        if (-not (Test-Path -Path (Split-Path -Path $FilePath -Parent))) {
            New-Item -Path (Split-Path -Path $FilePath -Parent) -ItemType Directory -Force | Out-Null
        }
        $Items = @{ $BPAServer = $Credential }
    }
    $Items | Export-Clixml -Path $FilePath
}