# Read the username from DefaultUsername.txt try { $defaultUsername = Get-Content -Path ".\DefaultUsername.txt" -ErrorAction Stop Write-Host "Using username from file: $defaultUsername" } catch { Write-Host -ForegroundColor Red "Failed to read DefaultUsername.txt: $_" exit 1 } # Prompt for credentials, prepopulating the username $credential = Get-Credential -UserName $defaultUsername -Message "Enter your domain admin credentials" try { # Import the Active Directory module Import-Module ActiveDirectory -ErrorAction Stop # Get the domain information $domain = (Get-ADDomain -ErrorAction Stop).DNSRoot Write-Host "Domain detected: $domain" # Construct the LDAP path for your domain $ldapPath = "LDAP://$domain" # Create a DirectoryEntry object for the LDAP connection $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry($ldapPath, $credential.UserName, $credential.GetNetworkCredential().Password) # Perform a simple query to validate credentials $searcher = New-Object System.DirectoryServices.DirectorySearcher($directoryEntry) $searcher.Filter = "(objectClass=User)" $result = $searcher.FindOne() if ($result -ne $null) { Write-Host -ForegroundColor Green "Credentials are valid. Authentication succeeded." # Try to export credentials securely try { Export-Clixml -Path ".\AdminCredential.xml" -InputObject $credential Write-Host -ForegroundColor Green "Credentials stored securely for the session." } catch { Write-Host -ForegroundColor Red "Failed to export credentials: $_" } } else { Write-Host -ForegroundColor Red "Invalid credentials. Authentication failed." } } catch { Write-Host -ForegroundColor Red "An error occurred during authentication: $_" }