Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Get-CredentialFromSecureStore
- {
- [cmdletbinding()]
- param
- (
- [Parameter(Mandatory=$true)][string]$TargetApplicationId
- )
- begin
- {
- [void][Reflection.Assembly]::LoadFile("C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.Office.SecureStoreService.Server.Security.dll")
- }
- process
- {
- $contextSite = Get-SPSite -Limit 1 -WarningAction SilentlyContinue -Verbose:$false
- $serviceContext = Get-SPServiceContext -Site $contextSite -Verbose:$false
- $provider = New-Object Microsoft.Office.SecureStoreService.Server.SecureStoreProvider
- $provider.Context = $serviceContext
- $credentials = $provider.GetRestrictedCredentials($TargetApplicationId)
- $credentials | % {
- $credential = $_.Credential
- switch ($_.CredentialType)
- {
- "WindowsUserName"
- {
- $marshal = [System.Runtime.InteropServices.Marshal]
- $ptr = $marshal::SecureStringToBSTR($credential)
- $plainTextUserName = [string]::Copy($marshal::PtrToStringBSTR($ptr))
- $marshal::ZeroFreeBSTR($ptr)
- }
- "WindowsPassword"
- {
- $marshal = [System.Runtime.InteropServices.Marshal]
- $ptr = $marshal::SecureStringToBSTR($credential)
- $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
- $marshal::ZeroFreeBSTR($ptr)
- }
- "UserName"
- {
- $marshal = [System.Runtime.InteropServices.Marshal]
- $ptr = $marshal::SecureStringToBSTR($credential)
- $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
- $marshal::ZeroFreeBSTR($ptr)
- }
- "Password"
- {
- $marshal = [System.Runtime.InteropServices.Marshal]
- $ptr = $marshal::SecureStringToBSTR($credential)
- $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
- $marshal::ZeroFreeBSTR($ptr)
- }
- }
- }
- if($credentials)
- {
- $credentials.Dispose()
- }
- if( $plainTextUserName -and $unSecurePassword )
- {
- Write-Verbose "Username: $($plainTextUserName)"
- Write-Verbose "Password: $($unSecurePassword)"
- $secureString = New-Object System.Security.SecureString
- $unSecurePassword.ToCharArray() | % { $secureString.AppendChar($_) }
- $psCredential = New-Object PSCredential($plainTextUserName, $secureString)
- return $psCredential
- }
- return $null
- }
- end
- {
- }
- }
- Get-CredentialFromSecureStore -TargetApplicationId "Test" -Verbose
Add Comment
Please, Sign In to add comment