dear all, i have tried to use a lot of scripts to add computer to domain in a secure way , so that the password will not be shown as plain text in any way . , but each time i failed , here is my last try… if i run the script the creds are wrong, or null … help will be appreciated .
Blockquote
function Store-Credential {
param (
[string]$Target
)
$cred = Get-Credential -Message “Enter your domain credentials:”
# pass domain\username format to cmdkey
$username = “$($cred.GetNetworkCredential().Domain)$($cred.GetNetworkCredential().UserName)”
cmdkey /add:$target /user:$username /pass:$($cred.GetNetworkCredential().Password)
}
Store the Crednetials
$Target = ‘DomainCreds’
Store-Credential -target $Target -persist Session
Function to Retrieve the creds from Windows Credential Manager
function Get-SecureCredential {
param (
[string]$target
)
$cred = New-Object System.Management.Automation.PSCredential(
(cmdkey /list:$target | Select-String -Pattern ‘user’ | ForEach-Object { $.ToString().Split(‘:’)[1].Trim() }),
(ConvertTo-SecureString (cmdkey /list:$Target | Select-String -Pattern ‘Pass’ | ForEach-Object { $.ToString().Split(‘:’)[1].Trim() }) -AsPlainText -Force)
)
return $cred
}
Set-ExecutionPolicy Unrestricted -Force
Import-Module CredentialManager
$target = ‘DomainCreds’
$credUsername = “DOMAIN\Username” # replace with the correct domain and username
Convert to PSCredential object for the add-computer command
$password = (cmdkey /list:$target | Select-String “Password”) -replace “Password\s+:\s+”
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$managedCreds = New-Object System.Management.Automation.PSCredential($credUsername, $securePassword)
$domain = Read-Host -Prompt ‘Enter Domain’
$ou = “OU=Computers,OU=Company,DC=mydomain,DC=local”
$cred = Get-SecureCredential -target $target
Write-Output “adding pc to the domain…”
add-computer -DomainName $domain -Credential $cred
cmdkey /delete:$target