Skip to content

Instantly share code, notes, and snippets.

@AceOfNitwits
Last active February 6, 2020 17:58
Show Gist options
  • Select an option

  • Save AceOfNitwits/ffa6bcf706de1e34aee7735e8218548c to your computer and use it in GitHub Desktop.

Select an option

Save AceOfNitwits/ffa6bcf706de1e34aee7735e8218548c to your computer and use it in GitHub Desktop.
Securely write and read powershell credentials to disk
Function Export-Credentials{
<#
.PARAMETER Path
The full path to the csv file where credentials will be stored.
.DESCRIPTION
Prompts for a username and password, then saves them to a csv file that the user specifies.
The password will be encrypted, and is only usable on the machine and under the user profile in which it was created.
.NOTES
The csv file will be overwritten without prompting.
#>
param(
[Parameter(Mandatory)][string]$Path
)
$creds = Get-Credential
$username = $creds.UserName
$encPassword = $creds.Password | ConvertFrom-SecureString
[pscustomobject]@{Username=$username;Password=$encPassword} | Export-Csv -Path $Path -NoTypeInformation
}
Function Import-Credentials{
<#
.PARAMETER Path
The full path to the csv file where credentials are stored.
.PARAMETER PlainText
Returns the password in plain text instead of as a SecureString object.
.DESCRIPTION
Imports a previously created CSV file.
Returns a PSCredential object or a PSCustomObject depending on the parameters.
#>
param(
[Parameter(Mandatory)][string]$Path,
[Parameter()][switch]$PlainText
)
$encCreds = Import-Csv -Path $Path
$username = $encCreds.Username
$encPassword = $encCreds.Password
$secPassword = ConvertTo-SecureString $encPassword
$secCreds = New-Object System.Management.Automation.PSCredential($username,$secPassword)
If($PlainText){
$securePw = $secCreds.Password
# Extracting the password from a PSCredential object is a two-step process.
$pwBstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePw)
$pwString = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pwBstr)
# 🧹 Cleanup
[Runtime.InteropServices.Marshal]::FreeBSTR($pwBstr)
[pscustomobject]@{UserName=$secCreds.UserName; Password=$pwString}
}
Else{
$secCreds
}
}
Export-ModuleMember -Function *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment