Skip to content

Instantly share code, notes, and snippets.

@ScriptingPro
Created November 28, 2018 00:10
Show Gist options
  • Save ScriptingPro/d14d85c4e58e3ad9d2322be346dcccf4 to your computer and use it in GitHub Desktop.
Save ScriptingPro/d14d85c4e58e3ad9d2322be346dcccf4 to your computer and use it in GitHub Desktop.
save powershell credential to xml
<#
powershell save credentials to xml file
export-clixml powershell credentials
powershell save credentials to disk
powershell script credential file
powershell write credential to file
#>
# this way for v4
function savecred
{
param
(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=0)][string]$UPN = $([adsisearcher]([ADSI]"LDAP://<SID=$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)>")).FindOne().Properties.userprincipalname,
[Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=1)][string]$Password
)
$SecureString = ConvertTo-SecureString $Password -AsPlainText -Force
$PSCredential = New-Object System.Management.Automation.PSCredential($UPN,$SecureString)
Export-Clixml -InputObject $PSCredential -Path ($env:USERPROFILE + "\cred\" + $PSCredential.UserName.Replace("\","-") + ".xml")
}
# this way for v5
function savecred
{
param
(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=0)][string]$UPN = $([adsisearcher]([ADSI]"LDAP://<SID=$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)>")).FindOne().Properties.userprincipalname,
[Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=1)][string]$Password
)
[System.Management.Automation.PSCredential]::new($UPN,$(ConvertTo-SecureString -String $Password -AsPlainText -Force)) | %{Export-Clixml -InputObject $_ -Path ($env:USERPROFILE + "\cred\" + $_.UserName.Replace("\","-") + ".xml")}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment