Skip to content

Instantly share code, notes, and snippets.

@pmsmith
Created February 9, 2018 22:05
Show Gist options
  • Save pmsmith/240821b34838675af06965687ac999d2 to your computer and use it in GitHub Desktop.
Save pmsmith/240821b34838675af06965687ac999d2 to your computer and use it in GitHub Desktop.
AddSavedCredential.ps1
param([Parameter(Mandatory=$true)][string]$hostname)
#-----------------------------------------------------------------------
#- Get-SavedCredentials
#-----------------------------------------------------------------------
function Get-SavedCredentials {
$savedCredentials = C:\Windows\System32\cmdkey.exe /list | Select-String 'TERMSRV/' | ForEach-Object {
Write-Output ($_.ToString().Replace('Target: LegacyGeneric:target=','')).Trim()
}
return $savedCredentials
}
#-----------------------------------------------------------------------
#- Remove-SavedCredentials
#-----------------------------------------------------------------------
Function Remove-SavedCredentials {
Get-SavedCredentials | ForEach-Object {
$formattedEntry = $_.Replace('Target: Domain:target=','')
C:\Windows\System32\cmdkey.exe /delete:$formattedEntry
}
}
#-----------------------------------------------------------------------
#- Add-SavedCredential
#-----------------------------------------------------------------------
Function Add-SavedCredential {
param([string]$hostname,[string]$savedCredentialPath='C:\users\paul\Documents\encCrd.xml')
$ec = Import-CliXML -Path $savedCredentialPath
$username = $ec.Username.ToString().Trim()
$password = $ec.GetNetworkCredential().Password.ToString().Trim()
C:\Windows\System32\cmdkey.exe /generic:TERMSRV/$hostname /user:$username /pass:$password
Remove-Variable ec,username,password
}
#-----------------------------------------------------------------------
#- Main
#-----------------------------------------------------------------------
Remove-SavedCredentials
Add-SavedCredential -hostname $hostname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment