I've saved a SecureString with ConvertFrom-SecureString to a file and have code to extract and convert the encrypted string back to a SecureString. However, when using the SecureString to authenticate and query a domain with DirectoryServices.DirectorySearcher the query fails with a logon error.
I know the encrypted string is saved and retrieved correctly because I can convert the SecureString to plan text and used it to successfully query. What am I doing wrong, is there a better way to accomplish this query? Thanks in advance!
#Create file with encrypted string (outside of main script)
$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
read-host -assecurestring | convertfrom-securestring -key $key | out-file C:\temp\cred.txt
$computer = $env:computername
#Get encrypted string and convert to secure string
$password = get-content C:\Temp\cred1.txt | convertto-securestring -Key $key
$domain = New-Object DirectoryServices.DirectoryEntry("LDAP://you.domain.here","domain\username", $PASSWORD)
$search = New-Object DirectoryServices.DirectorySearcher($domain)
$search.filter = "(&(objectClass=computer)(name=$computer))"
$script:search.findall() | %{$_.GetDirectoryEntry() }
Write-Host $searchresult.distinguishedName
If I convert the encrypted string to plain text then I’m able to successfully query the domain I’m not a member of.
$computer = $env:computername
#Get encrypted string and convert to secure string
$password = get-content C:\Temp\cred1.txt | convertto-securestring -Key $key
#Convert to plain text string
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$domain = New-Object DirectoryServices.DirectoryEntry("LDAP://you.domain.here","domain\username", $PlainPASSWORD)
$search = New-Object DirectoryServices.DirectorySearcher($domain)
$search.filter = "(&(objectClass=computer)(name=$computer))"
$script:search.findall() | %{$_.GetDirectoryEntry() }