1+ function ConvertTo-PSCredential {
2+ <#
3+ . Synopsis
4+ Converts the result of Get-VaultKVSecret or Get-VaultCubbyhole into a PSCredential.
5+
6+ . DESCRIPTION
7+ ConvertTo-PSCredential consumes the result of Get-VaultKVSecret or Get-VaultCubbyhole and converts the resulting object into a PSCredential.
8+
9+ . EXAMPLE
10+ PS> Get-VaultKVSecret -Engine dsc -SecretsPath DSCSvcAccount | ConvertTo-PSCredential
11+
12+ UserName Password
13+ -------- --------
14+ WAYFAIRDEV\sa_dscadmin System.Security.SecureString
15+
16+ . EXAMPLE
17+ PS> ConvertTo-PSCredential -InputObject $(Get-VaultKVSecret -Engine dsc -SecretsPath DSCSvcAccount)
18+
19+ UserName Password
20+ -------- --------
21+ WAYFAIRDEV\sa_dscadmin System.Security.SecureString
22+
23+ #>
24+ [CmdletBinding ()]
25+ param (
26+ # Specifies the Input Object. The input object can be in the form of a Hashtable, PSObject or JSON string.
27+ [Parameter (
28+ ValueFromPipeline = $true ,
29+ Position = 0
30+ )]
31+ $InputObject
32+ )
33+
34+ begin {
35+ # Array of supported functions.
36+ $supportedFunctions = @ (
37+ ' Get-VaultKVSecret'
38+ ' Get-VaultCubbyholeSecret'
39+ )
40+
41+ $psCallStack = Get-PSCallStack
42+
43+ foreach ($funct in $supportedFunctions ) {
44+ $callStackPosition = $psCallStack | Where-Object ' Position' -match $funct
45+
46+ if ($callStackPosition ) {
47+ break
48+ }
49+ }
50+
51+ if ($psCallStack -notmatch " |" ) {
52+ # Pipeline was present.
53+ if (-not $callStackPosition ) {
54+ Write-Error " ConvertTo-PSCredential does not support the specified pipeline input." - ErrorAction ' Stop'
55+ return
56+ }
57+ }
58+ # else Pipeline not present.
59+
60+ }
61+
62+ process {
63+ if ($InputObject -is [Hashtable ]) {
64+ Write-verbose ' Input is hashtable'
65+ $InputObject = ConvertFrom-Hashtable $ ([hashtable ] $InputObject )
66+ }
67+ elseif ($InputObject -is [String ]) {
68+ Write-verbose ' Input is string'
69+ try {
70+ $InputObject = $InputObject | ConvertFrom-Json
71+ Write-verbose ' converted json to psobject'
72+ }
73+ catch {
74+ Write-Error " The specified JSON is malformed and could not be converted to a PSCredential"
75+ return
76+ }
77+ }
78+ else {
79+ Write-verbose ' Input is psobject'
80+ }
81+
82+ $result = Format-VaultOutput - InputObject $InputObject - DataType ' secret_data' - OutputType ' Hashtable' - JustData:$true
83+
84+ if (-not $result ) {
85+ # If there was no result, the secret could be a Cubbyhole secret; try a different DataType.
86+ $result = Format-VaultOutput - InputObject $InputObject - DataType ' data' - OutputType ' Hashtable' - JustData:$true
87+ }
88+
89+ if ($result ) {
90+ New-Object System.Management.Automation.PSCredential (
91+ $result.Keys [0 ],
92+ (ConvertTo-SecureString ($result.Values [0 ]) - AsPlainText - Force)
93+ )
94+ }
95+
96+ }
97+
98+ end {
99+
100+ }
101+ }
0 commit comments