how to provide server/OU/DC details to [adsisearcher]? - powershell

$ADResult = ([adsisearcher]"(samaccountname=$sams)").Findone()
I am using this statement to search in the AD the accounts with the samaccountnames as $sams, but the problem is that Im calling this from a different server and not from the one where AD's exist.
So, what I need to know is can I provide it details of the following -
Server
DC
OU
and if yes, HOW?

Set variables for your Domain Controller, Domain, Suffix and OU like this:
$DC = "DCServer"
$Domain = "MyDomain"
$Sufix = "Local"
$OU = "MyOU"
$SAMName = "SamAccountName"
Link your Searcher object to that info...
$Root = [adsi] "LDAP://$DC/OU=$OU,DC=$Domain,DC=$Suffix"
$Searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$Searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
$Searcher.FindOne()
If you have Sub-OU's Add OU="OU1",OU="OU2" etc.

Related

PowerShell - How do I add a User to an AD User Group using ADSI and alternate credentials

I need to add a user to an AD Group using specific credentials and cannot figure this out.... Here's what I have so far which gives me an "unspecified error" retrieving member 'Add'. Must be done using ADSI as the AD module won't work in my scenario.
$CredsUserName = 'domain\user'
$CredsPassword = 'password'
$GroupPath = "LDAP://CN=<UserGroup>...."
$UserPath = "LDAP://CN=<UserDN>...."
$Group = [ADSI]$GroupPath
$User = [ADSI]$UserPath
$GroupArgs = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $Group, "$CredsUserName", "$CredsPassword"
$GroupArgs.Add($User.adspath)
Try this:
$CredsUserName = 'domain\user'
$CredsPassword = 'password'
$Domain = "<FQDN of the AD domain>/"
$GroupPath = "CN=<UserGroup>...."
$UserPath = "CN=<UserDN>...."
$Group = [adsi]::new("LDAP://$($Domain)$($GroupPath)",$CredsUserName,$CredsPassword)
$Group.member.Add($UserPath)
$Group.CommitChanges()
You only need $Domain if the computer you are using isn't part of the AD domain that contains the group.
Regards,
Stuart.

PowerShell: How to add 1 user to multiple Active Directory Security Groups - Security tab of the security group with write permission

I am trying to add 1 ID to multiple security groups in Active Directory.
The ID needs to be only added to the "Security Tab" of the Security Group and not added as a member.
I need to set "write" permission for this ID.
Is there anyways to do this in Power-Shell?
There are instructions here, although that gives a user full control of the group (including rights to delete), and has some other issues (like a hard-coded username).
I've modified that example for you to only give GenericWrite permissions, and to accept the username as a parameter. This also assumes the user, group, and computer you're running this on are all on the same domain:
function Set-GroupSecurity {
[CmdletBinding()]
param (
[string] $GroupName,
[string] $UserName
)
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(&(objectclass=group)(sAMAccountName=$GroupName))"
$search.SizeLimit = 3000
$result = $search.FindOne()
$object = $result.GetDirectoryEntry()
$sec = $object.ObjectSecurity
## set the rights and control type
$allow = [System.Security.AccessControl.AccessControlType]::Allow
$read = [System.DirectoryServices.ActiveDirectoryRights]::GenericRead
$write = [System.DirectoryServices.ActiveDirectoryRights]::GenericWrite
## who does this apply to
$domname = ([ADSI]"").Name
$who = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "$domname", $UserName
# apply rules
$readrule = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $who, $read, $allow
$sec.AddAccessRule($readrule)
$writerule = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $who, $write, $allow
$sec.AddAccessRule($writerule)
# tell it that we're only changing the DACL and not the owner
$object.get_Options().SecurityMasks = [System.DirectoryServices.SecurityMasks]::Dacl
# save
$object.CommitChanges()
}
You can paste that into a PowerShell prompt and hit enter. That will make the function available to use. Then you can use it like this:
Set-GroupSecurity -GroupName "TstGroup1" -UserName "someone"

Get Current User URI for Lync 2013 via PowerShell

I'm am trying to get the current user's URI that is signed into Lync on the machine the PS script is run on. I've Googled to no avail. One method I thought of trying was to get the Windows logged in name and then parse that into an e-mail address but there will be instances in which this won't give the correct URI. Is this achievable?
Assuming I understand your question...
1) Getting sip-address for current user using the ActiveDirectory-module.
(Get-ADUser $env:USERNAME -Properties msRTCSIP-PrimaryUserAddress).'msRTCSIP-PrimaryUserAddress'
2) Getting sip-address for current user using DirectorySearcher.
$filter = "(&(objectCategory=User)(SamAccountName=$env:USERNAME))"
$property = 'msRTCSIP-PrimaryUserAddress'
$domain = New-Object System.DirectoryServices.DirectoryEntry
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = $domain
$Searcher.PageSize = 1000
$Searcher.Filter = $Filter
$Searcher.SearchScope = "Subtree"
$Searcher.PropertiesToLoad.Add($property) | Out-Null
# Value
($Searcher.FindAll()).Properties[$property]

Change user mail property with ADSI in PowerShell

I am trying to update the email address of a directory user with PowerShell.
I am unable to modify the mail property of a user entry with the following code:
$BadUser = [adsi] $Account.Path
$BadUser.mail.Clear()
$BadUser.mail.Add($User.Email) | Out-Null
$BadUser.SetInfo()
The mail.Clear() nor the mail.Add() seem to modify $BadUser when debugging with PowerGUI.
I have a working version that relies on the QAD plugin, and I would like to avoid using it if possible.
$suf = $AD.Parent.Substring(10)
Connect-QADService -Service "$($AD.dc[0]).$suf" -ErrorVariable AD_Conn_Error -ErrorAction Stop -WarningAction Stop | Out-Null
Set-QADObject $Account.Properties.distinguishedname[0] -ObjectAttributes #{mail=$User.Email} | Out-Null
Disconnect-QADService
Reasons I am avoiding QAD:
I am searching for users across 8 domain servers
ADSI allows me to save multiple connected entries in a list
QAD can connect to 1 domain at a time
ADSI seems relatively fast
QAD has memory leaks (1kB/s bad) that crash in large batches
QAD is unable to "identify" some users that ADSI found by cn
Here's some example code to do it:
$query= "(&(objectCategory=User)(cn=FirstName LastName))"
$OU = "LDAP://OU=Users,dc=subdomain,dc=company,dc=com"
$PageSize = 100
$objOU = New-Object System.DirectoryServices.DirectoryEntry($OU)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objOU
$objSearcher.PageSize = $PageSize
$objSearcher.Filter = $query
$objSearcher.SearchScope = "Subtree"
$colResults = $objSearcher.FindAll()
foreach($objResult in $colResults) {
$dirObject = [ADSI]$objResult.GetDirectoryEntry()
$dirObject.mail = "newaddress#company.com"
$dirObject.CommitChanges()
}

Powershell Bulk Find ActiveDirectory Objects

I'm trying to develop a powershell script to help with AD Group Membership management. We have a handful of large groups (30k-60k+ objects) that we want to update with data from another system.
The script loads the objects that should be in the group from a text file. Each object then has to located in AD using a System.DirectoryServices.DirectorySearcher. After that each object is added to the group membership.
The script spends some 80% of its time looking up each object, is there a bulk way to find objects in AD with powershell?
Thanks!
This is the fast way to query AD that I found in my experience, you need to change the query to find specific objects, in this code you'll find all user/person object in $objRecordSet.
$Ads_Scope_SubTree = 2
$objConnection = new-Object -com "ADODB.Connection"
$objCommand = new-Object -com "ADODB.Command"
$objConnection.Provider = "ADsDSOObject"
$objConnection.Open( "Active Directory Provider")
$objCommand.ActiveConnection = $objConnection
$objCommand.Properties.Item("Page Size").value = 1000
$objCommand.Properties.item("Searchscope").value = $Ads_Scope_SubTree
$objCommand.CommandText = "Select Name From 'LDAP://DC = int, DC= my, DC = local' Where objectCategory = 'Person'"
$objRecordSet = $objCommand.Execute()
$objRecordSet.RecordCount
More info here
You perhaps can try System.DirectoryServices.Protocols (S.DS.P) the native (non managed) version is quite efficient.
Here is a PowerShell starting script :
# ADDP-Connect.PS1
Clear-Host
# Add the needed assemblies
Add-Type -AssemblyName System.DirectoryServices.Protocols
# Connexion
$serverName = "WM2008R2ENT"
$ADDPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection $serverName
$userName = "JPB"
$pwd = "PWD"
$domain = "Dom"
$ADDPConnect.Credential = New-Object system.Net.NetworkCredential -ArgumentList $userName,$pwd,$domain
# Create a searcher
$searchTargetOU = "dc=dom,dc=fr"
$searchFilter = "(samAccountName=user1)"
$searchScope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$searchAttrList = $null
foreach($user in "user1","user2","user3")
{
$searchFilter = "(samAccountName=$user)"
$searchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $searchTargetOU,$searchFilter,$searchScope,$searchAttrList
$searchResponse = $ADDPConnect.SendRequest($searchRequest)
foreach($searchEntries in $searchResponse.Entries)
{
$searchEntries.DistinguishedName
}
}
If you start seeing timeout issues then set the timeout parameter appropriately like shown below
$ADDPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection $serverName
$ADDPConnect.Timeout = "1000"
The below can help if you see timeout issues during execution
$ADDPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection $serverName
$ADDPConnect.Timeout = "1000"