Set-VaultCredential.ps1

<#
.SYNOPSIS
  Store the given credential in the PasswordVault for a given resource.
.PARAMETER Resource
  The resource to remove from the PasswordVault
.PARAMETER User
  The user connected to the resource
.PARAMETER Password
  The password fot the given user
.PARAMETER Credential
  The user stored in Credential connected to the resource
 
.EXAMPLE
  Set-Credential -Resource https://msdn.microsoft.com -User CONTOSO\john.doe -Password 's3cr3t'
 
  Description
  -----------
  Stores the credentials for the user john.doe on domain CONTOSO for the resource https://msdn.microsoft.com
 
.EXAMPLE
  Set-Credential -Resource https://msdn.microsoft.com -Credential (Get-Credential CONTOSO\john.doe)
 
  Description
  -----------
  Stores the credentials for the user john.doe on domain CONTOSO for the resource https://msdn.microsoft.com
  The password will be asked in the dialog box generated by Get-Credential
#>

function Set-VaultCredential #{{{
{
  [CmdletBinding(DefaultParameterSetName='Credential')]
  Param(
    [Parameter(Position=1, Mandatory=$true, ValueFromPipeLine=$true, ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [string[]] $Resource,
    [Parameter(Position=2, ParameterSetName='Credential', Mandatory=$true, ValueFromPipelineByPropertyName = $true)]
    [System.Management.Automation.PSCredential] $Credential,
    [Parameter(Position=2, ParameterSetName='Plain', Mandatory=$true, ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [Alias('UserName', 'UserId', 'Name')]
    [string] $User,
    [Parameter(Position=3, ParameterSetName='Plain', Mandatory=$true, ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [string] $Password
  )
  process
  {
    $vault = New-Object Windows.Security.Credentials.PasswordVault
    $Resource | ForEach {
      if ($PSCmdlet.ParameterSetName -eq 'Credential')
      {
        $vault_credential = New-Object Windows.Security.Credentials.PasswordCredential $_,$Credential.UserName,$Credential.GetNetworkCredential().Password
      }
      else
      {
        $vault_credential = New-Object Windows.Security.Credentials.PasswordCredential $_,$User,$Password
      }
      $vault.Add($vault_credential)
    }
  }
} # }}}