Private/ConvertTo-InsecureString.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Function ConvertTo-InsecureString {
    <#
    .SYNOPSIS
    Returns string value from SecureString input

    .DESCRIPTION
    Gets the decoded string value of an encoded SecureString

    .PARAMETER SecureString
    The SecureString to decode

    .EXAMPLE
    ConvertTo-InsecureString $SecureStringValue
    #>

    [CmdLetBinding()]
    [OutputType('System.String')]
    Param (

        [Parameter(
            Mandatory = $True,
            ValueFromPipeline = $True
        )]
        [System.Security.SecureString]$SecureString
    )

    Process {
        Try {

            $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($SecureString)
            [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)

        }

        Finally {

            [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr)

        }
    }
}