Using Credential Vault Credentials

This article describes an example of using credentials retrieved from the Windows Credential Vault in PowerShell to perform a privileged operation. In this example, we will use the credentials to join a workgroup computer to a domain.

Joining a workgroup computer to a domain

We assume that we have already used the set-1ECredential cmdlet to send appropriately privileged credentials to a workgroup computer. Note that the domain name in this PowerShell example is hard coded. You would want to pass this in as a parameter to the script.

We retrieve the credential from the Credential Vault assuming that it was stored with the name AdminCreds. This code is assumed to be run in the context of the account in which those credentials were stored, which almost certainly will be LocalSystem.

Having retrieved the credentials, we then need to convert them into a PSCredential object as they cannot be used directly in most PowerShell commands that require credentials.

The Credential Vault returns a different object type; however, you can easily convert it by retrieving the account and password from the vault credential, and then re-encoding them into a PSCredential object.

Having joined the domain, we force a reboot by using the start command. Note that the obvious native PowerShell solution, which would use start-job and then sleeping for 30 seconds before using the restart-computer cmdlet, does not work as expected because if this script is run from the 1E Client, then the PowerShell session is destroyed before the asynchronous job sleep command has completed. At that point, the entire asynchronous task is canceled, and the computer never reboots. Hence, we use start to kick off a shutdown with a 30-second delay instead.

Copy
[void]([Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime])
$vault = New-Object Windows.Security.Credentials.PasswordVault
$creds = $vault.RetrieveAll()
$mycred = $creds | where-object {$_.Resource -eq "AdminCreds"}
if ($null -eq $mycred)
    {
    throw "The specified credentials could not be retrieved"
    }
 
$mycred.RetrievePassword()
[securestring]$secPassword = convertto-securestring $myCred.Password -AsPlainText -Force
[pscredential]$credObject = new-object system.management.automation.pscredential ($mycred.UserName,$secPassword)
Add-Computer -Domain urth.local -Credential $credObject
$a = @("/c","start", "shutdown","/r", "/t 30",'/c " "')
Start-Process "cmd" -ArgumentList $a