Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

IT-Wiki

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View my Codeberg Page

View my Photo Website

Export- und Import-Clixml

published: July 22, 2016 author: Tinu tags: Authentication - PSObject - XML categories: PowerShell


Export-Clixml und Import-Clixml mit Credentials

By default, the SecureString cmlets (ConvertFrom-SecureString and ConvertTo-SecureString) use Windows’ Data Protection API when they convert your SecureString to and from a plain text representation. The encryption key is based on your Windows logon credentials so only you can decrypt the data that you’ve encrypted. If you want the exported data to work on another system or separate user account, you can use the parameter sets “-Key $Key” that let you provide an explicit key.

function Export-CredentialToXML
{
 [CmdletBinding()]
 param (
    [Parameter (Mandatory = $true)] [pscredential] $Credential,
    [Parameter (Mandatory = $true)] [string] $Path
 )
 $key = New-Object byte[](32)
 $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
 $rng.GetBytes($key)
 $export = ConvertFrom-SecureString -SecureString $Credential.Password -Key $key
 New-Object psobject -Property @{ Key = $key; UserName = $Credential.UserName; Password = $export } |
 Export-CliXml -Path $Path
}

function Import-CredentialFromXML
{
 [CmdletBinding()]
 param (
    [Parameter (Mandatory = $true)] [string] $Path
 )
 try
 {
    $object = Import-Clixml -Path $Path -ErrorAction Stop
    $secureString = ConvertTo-SecureString -String $object.Password -Key $object.Key -ErrorAction Stop
    return New-Object pscredential($object.UserName, $secureString)
 }
 catch
 {
    throw
 }
}

# To export to a file:
$originalCred = Get-Credential
Export-CredentialToXML -Credential $originalCred -Path '.\test.xml'

# To read it back in:
$newCred = Import-CredentialFromXML -Path '.\test.xml'
$newCred.GetNetworkCredential() | Format-List *

← Previous Post ◇ [ Top ] ◇ Copyright © 2024 by tinuwalther ◇ [ Blog ] ◇ Next Post →