Guest User

Untitled

a guest
Jun 27th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.95 KB | None | 0 0
  1. function Get-CredentialFromSecureStore
  2. {
  3. [cmdletbinding()]
  4. param
  5. (
  6. [Parameter(Mandatory=$true)][string]$TargetApplicationId
  7. )
  8.  
  9. begin
  10. {
  11. [void][Reflection.Assembly]::LoadFile("C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.Office.SecureStoreService.Server.Security.dll")
  12. }
  13. process
  14. {
  15. $contextSite = Get-SPSite -Limit 1 -WarningAction SilentlyContinue -Verbose:$false
  16. $serviceContext = Get-SPServiceContext -Site $contextSite -Verbose:$false
  17. $provider = New-Object Microsoft.Office.SecureStoreService.Server.SecureStoreProvider
  18. $provider.Context = $serviceContext
  19.  
  20. $credentials = $provider.GetRestrictedCredentials($TargetApplicationId)
  21.  
  22. $credentials | % {
  23.  
  24. $credential = $_.Credential
  25.  
  26. switch ($_.CredentialType)
  27. {
  28. "WindowsUserName"
  29. {
  30. $marshal = [System.Runtime.InteropServices.Marshal]
  31. $ptr = $marshal::SecureStringToBSTR($credential)
  32. $plainTextUserName = [string]::Copy($marshal::PtrToStringBSTR($ptr))
  33. $marshal::ZeroFreeBSTR($ptr)
  34. }
  35.  
  36. "WindowsPassword"
  37. {
  38. $marshal = [System.Runtime.InteropServices.Marshal]
  39. $ptr = $marshal::SecureStringToBSTR($credential)
  40. $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
  41. $marshal::ZeroFreeBSTR($ptr)
  42. }
  43.  
  44. "UserName"
  45. {
  46. $marshal = [System.Runtime.InteropServices.Marshal]
  47. $ptr = $marshal::SecureStringToBSTR($credential)
  48. $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
  49. $marshal::ZeroFreeBSTR($ptr)
  50. }
  51.  
  52. "Password"
  53. {
  54. $marshal = [System.Runtime.InteropServices.Marshal]
  55. $ptr = $marshal::SecureStringToBSTR($credential)
  56. $unSecurePassword = [string]::Copy($marshal::PtrToStringBSTR($ptr))
  57. $marshal::ZeroFreeBSTR($ptr)
  58. }
  59. }
  60. }
  61.  
  62. if($credentials)
  63. {
  64. $credentials.Dispose()
  65. }
  66.  
  67. if( $plainTextUserName -and $unSecurePassword )
  68. {
  69. Write-Verbose "Username: $($plainTextUserName)"
  70. Write-Verbose "Password: $($unSecurePassword)"
  71.  
  72. $secureString = New-Object System.Security.SecureString
  73. $unSecurePassword.ToCharArray() | % { $secureString.AppendChar($_) }
  74.  
  75. $psCredential = New-Object PSCredential($plainTextUserName, $secureString)
  76. return $psCredential
  77. }
  78.  
  79.  
  80. return $null
  81. }
  82. end
  83. {
  84. }
  85. }
  86.  
  87. Get-CredentialFromSecureStore -TargetApplicationId "Test" -Verbose
Add Comment
Please, Sign In to add comment