I was automating some Azure DevOps tasks using a scheduled task and PowerShell and needed the ability to authenticate. As the credentials should not be in clear text in the script I wanted to use the Windows Credential Manager.

[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$vaultCredential = `
  $vault.Retrieve(`
    $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, `
    `$env:USERNAME);

if($vaultCredential -eq $null){
  Write-Host "The credentials must be created first...";
  Write-Host "User name: $env:USERNAME" -ForegroundColor DarkGray;
  Write-Host "Password: " -NoNewline;

  $value =
    [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(`
      [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(`
        (Read-Host -AsSecureString)))

  $vaultCredential = `
    New-Object Windows.Security.Credentials.PasswordCredential(`
      $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, `
      "$env:USERNAME", "$value");

  $vault.Add($vaultCredential);
  Write-Host "The credentials was stored to the credential manager";
}

$vaultCredential = `
  $vault.Retrieve(`
    $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, `
    $env:USERDOMAIN);

$vaultCredential.RetrievePassword();

$credential = `
  New-Object System.Net.NetworkCredential(`
    $vaultCredential.UserName, `
    $vaultCredential.Password, `
    $env:USERDOMAIN);