1
+ function Export-PSCredential {
2
+ <#
3
+ . SYNOPSIS
4
+ Export credentials to a file
5
+
6
+ . DESCRIPTION
7
+ Export credentials to a file
8
+ For use with Import-PSCredential
9
+ A credential can only be decrypted by the user who encryped it, on the computer where the command was invoked.
10
+
11
+ . PARAMETER Credential
12
+ Credential to export
13
+
14
+ . PARAMETER Path
15
+ File to export to. Parent folder must exist
16
+
17
+ . PARAMETER Passthru
18
+ Return FileInfo object for the credential file
19
+
20
+ . EXAMPLE
21
+
22
+ #Creates a credential, saves it to disk
23
+ $Credential = Get-Credential
24
+ Export-PSCredential -path C:\File.xml -credential $Credential
25
+
26
+ #Later on, import the credential!
27
+ $ImportedCred = Import-PSCredential -path C:\File.xml
28
+
29
+ . NOTES
30
+ Author: Hal Rottenberg <[email protected] >, butchered by ramblingcookiemonster
31
+ Purpose: These functions allow one to easily save network credentials to disk in a relatively
32
+ secure manner. The resulting on-disk credential file can only [1] be decrypted
33
+ by the same user account which performed the encryption. For more details, see
34
+ the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as
35
+ MSDN pages about Windows Data Protection API.
36
+ [1]: So far as I know today. Next week I'm sure a script kiddie will break it.
37
+
38
+ . FUNCTIONALITY
39
+ General Command
40
+ #>
41
+ [cmdletbinding ()]
42
+ param (
43
+ [parameter (Mandatory = $true )]
44
+ [pscredential ]$Credential = (Get-Credential ),
45
+
46
+ [parameter ()]
47
+ [Alias (" FullName" )]
48
+ [validatescript ({
49
+ Test-Path - Path (Split-Path - Path $_ - Parent)
50
+ })]
51
+ [string ]$Path = " credentials.$env: COMPUTERNAME .xml" ,
52
+
53
+ [switch ]$Passthru
54
+ )
55
+
56
+ # Create temporary object to be serialized to disk
57
+ $export = New-Object - TypeName PSObject - Property @ {
58
+ UserName = $Credential.Username
59
+ EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
60
+ }
61
+
62
+ # Export using the Export-Clixml cmdlet
63
+ Try
64
+ {
65
+ $export | Export-Clixml - Path $Path - ErrorAction Stop
66
+ Write-Verbose " Saved credentials for $ ( $export.Username ) to $Path "
67
+
68
+ if ($Passthru )
69
+ {
70
+ # Return FileInfo object referring to saved credentials
71
+ Get-Item $Path - ErrorAction Stop
72
+ }
73
+ }
74
+ Catch
75
+ {
76
+ Write-Error " Error saving credentials to '$Path ': $_ "
77
+ }
78
+ }
0 commit comments