I've been doing a lot of work inside Active Directory lately. The company that picked me up has numerous AD Domain trusts. To organize the collection of AD security credentials needed to perform audits on AD objects that are in different domains within the same script I created this security keyring. It's not perfect, but I good solid step in the right direction.
The first step is to call the 'AddKey' method. It will do the following:
- Prompt you for security credentials (user name and password) and store the credential object
- Connect to the domain you specified when calling 'AddKey' and store the connection object
How to access individual parameters:
$KeyRing.AddKey("abc.domain.com")
$KeyRing.Get_Item("abc.domain.com").Connection
$KeyRing.Get_Item("abc.domain.com").Credentials
How to use:
$KeyRing.AddKey("abc.domain.com")
$user = Get-QADObject -Connection ($KeyRing.GetItem("abc.domain.com").Connection) -Identity "Joe User"
To See all the entries:
$KeyRing
# Initialize a Security Keyring
$sscc = [system.stringcomparer]::CurrentCultureIgnoreCase;
$Keyring = New-Object System.Collections.Hashtable $sscc;
$Keyring = add-member -inputobject $Keyring `
-membertype ScriptMethod `
-name AddKey `
-value {
Param([string]$KeyName)
if ($this.Contains("$KeyName")) { return; }
$this.add("$KeyName",(New-Object PSObject));
# CREATE the Domain Name Object
$this.Set_Item("$KeyName", (Add-Member `
-Name "Domain_Name" `
-InputObject ($this.Get_Item("$KeyName")) `
-PassThru `
-MemberType NoteProperty `
-Value $KeyName));
# CREATE the Credentials Object
$this.Set_Item("$KeyName", (Add-Member `
-Name "Credentials" `
-InputObject ($this.Get_Item("$KeyName")) `
-PassThru `
-MemberType NoteProperty `
-Value (New-Object PSObject)));
# POPULATE the Credentials Object
$this.Get_Item("$KeyName").Credentials = $Host.UI.PromptForCredential("Need Credentials", `
"Please enter your user name and password for '$KeyName'.", `
"", `
"NetBiosUserName");
# CREATE the Connection Object
$this.Set_Item("$KeyName", (Add-Member `
-Name "Connection" `
-InputObject ($this.Get_Item("$KeyName")) `
-PassThru `
-MemberType NoteProperty `
-Value (New-Object PSObject)));
# POPULATE the Connection Object
try {
$this.Get_Item("$KeyName").Connection = Connect-QADService `
-service $KeyName `
-Credential ($this.Get_Item("$KeyName").Credentials);
}
catch {
$this.Get_Item("$KeyName").Connection = $_.Exception.toString();
}
# CREATE the Domain Identity Object
if ($this.Get_Item("$KeyName").Connection.getType().Name -ine "string") {
$this.Set_Item("$KeyName", (Add-Member `
-Name "Users_Domain_Identity" `
-InputObject ($this.Get_Item("$KeyName")) `
-PassThru `
-MemberType NoteProperty `
-Value ($this.Get_Item("$KeyName").Credentials.UserName.ToString())));
}
else {
$this.Set_Item("$KeyName", (Add-Member `
-Name "Users_Domain_Identity" `
-InputObject ($this.Get_Item("$KeyName")) `
-PassThru `
-MemberType NoteProperty `
-Value "N/A"));
}
} `
-passthru;