Get SAMAccountNames for all users in AD group - windows

I'm looking for a vbscript that will retrieve the SAMAccountNames for all members in a Active Directory Group.
Thanks.

Here is the script you are looking for :
' Begining from a given group
Dim strGrp
strGrp = "cn=g1,ou=ou,dc=societe,dc=fr"
Set objGroup = GetObject ("LDAP://"& strGrp)
objGroup.getInfo
arrMemberOf = objGroup.GetEx("member")
' Loop = For Each .... Next
' WScript.Echo "Members of Group "
For Each strMember in arrMemberOf
WScript.echo strMember
Set objUser = GetObject ("LDAP://"& strMember)
sAMAccountName = objUser.GetEx("sAMAccountName")
WScript.echo sAMAccountName(0)
Next
Wscript.Quit
Here is a site where you can get help.

Related

Through LDAP unable to read members of the domain admin group from Windows Server 2012

Trying to read domain admin group members through VBScript, but unable to read. Throwing error on user server.
object not a collection
But it's working in my local test Windows Server 2012.
User Running it from member server. User is having domain admin rights.
How to check LDAP issue in server or is their anything else?
Option Explicit
'Get all member of a group INCLUDING members from ALL NESTED groups.
'Simply call the script with the samAccountName of the group.
'If the group name contains spaces it should be ENCLOSED IN QUOTES,
'IE scriptName.vbs "DOMAIN ADMINS"
Dim objGroup
'verify a group name was passed
If WScript.Arguments.Count <> 1 Then
WScript.Echo "NO GROUP PASSED"
WScript.Echo "Usage: scriptName <groupSamAccountName>"
WScript.Quit
End If
'bind to the gorup
Set objGroup = getGroup(WScript.Arguments(0))
'enumerate the groups members
enumMembers objGroup, ""
Function getGroup(strGroupName)
Dim objConn, objRecSet, strQueryString, objRootDSE, strQueryFrom
Const adsOpenStatic = 3
Set objRootDSE = GetObject("LDAP://RootDSE")
strQueryFrom = "LDAP://" & objRootDSE.Get("defaultNamingContext")
Set objConn = WScript.CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open
strQueryString = "SELECT AdsPath FROM '" & strQueryFrom & "' " & _
"WHERE samAccountName = '" & strGroupName & "'"
Set objRecSet = WScript.CreateObject("ADODB.Recordset")
objRecSet.Open strQueryString, objConn, adsOpenStatic
If objRecSet.RecordCount = 1 Then
Set getGroup = GetObject(objRecSet("AdsPath"))
Else
WScript.Echo UCase(strGroupName) & " was not found in the domain.(" & objRootDSE.Get("defaultNamingContext") & ")"
WScript.Quit
End If
End Function
Sub enumMembers(ByRef objGroup, strInheritedFrom)
Dim objMember
For Each objMember In objGroup.Members '<---throwing error by saying "object not a collection"
If LCase(objMember.class) = "group" Then
WScript.Echo objMember.SamAccountName
End If
Next
End Sub

How to retrieve All attributes of given user from given group in ActiveDirectory using VBScript?

Can anyone help me to get All Attributes of given user in given group from active-directory using Vb Script .
On Error Resume Next
Set objGroup = GetObject _
("LDAP://CN=Domain Admins,CN=Users,DC=IMTS,DC=TEST")
objGroup.GetInfo
arrMemberOf = objGroup.GetEx("member")
WScript.Echo "Members:"
For Each strMember in arrMemberOf
WScript.echo strMember.distinguishedName
Next
This is giving me only users in group but i want all attributes on given user
eg:
Account_Expires:
Account_Name_History:
CS_PolicyName:
Admin_Count:
Admin_Description:
Admin_DisplayName:
AllowedAttributes:
AllowedAttributesEffective:
Allowed_Child_Classes:
AllowedChildClassesEffective:
AltSecurityIdentities:
AttributeCertificateAttribute:
Audio:
Bad_Password_Time:
Bad_Pwd_Count:
Bridge_head_ServerListBL:
BusinessCategory:
C:
canonicalName:
carLicense:
co:
So on
Thanks
note: Sorry, I'm not in an environment where I could test it and all this answer is just a memory exercise. I hope it can help
You could try to query the LDAP schema for the User class
Set oSchema = GetObject("LDAP://schema/user")
Then, you can iterate over the MandatoryProperties and OptionalProperties collections storing the retrieved values to later check your users for these attributes
Set oAttributesList = WScript.CreateObject("Scripting.Dictionary")
For Each strAttribute In oSchema.MandatoryProperties
oAttributesList.Add strAttribute, ""
Next
For Each strAttribute In oSchema.OptionalProperties
oAttributesList.Add strAttribute, ""
Next
And once you have the full list, you could use GetEx to retrieve (as an array) the value of each of the attributes for each of the users
Set objGroup = GetObject _
("LDAP://CN=Domain Admins,CN=Users,DC=IMTS,DC=TEST")
objGroup.GetInfo
arrMemberOf = objGroup.GetEx("member")
WScript.Echo "Members:"
For Each strMember in arrMemberOf
Set oMember = GetObject("LDAP://" & strMember)
For Each strAttribute in oAttributesList.Keys
WScript.Echo strAttribute
aData = oMember.GetEx(strAttribute)
For i = 0 to UBound(aData)
WScript.Echo "....: " & aData(i)
Next
WScript.Echo ""
Next
Next

VBScript \ Active Directory Searched by displayname and received 2 of the same

I have my script to search by displayname and return the userid, which works fine.
but when I encounter a displayname that has 2 entries in AD i.e.
pavle stojanovic - he is from company 1
pavle stojanovic - he is from company 2
the userid doesnt get displayed because the script doesnt know what to do ?
how do i over come this ? if I get a return of 2 or more I'd like to say in the output hey i found the same name twice etc.. here are the userids and companies for both.
If you want to see the script its below...
strFile = objFSO.GetParentFolderName(Wscript.ScriptFullName) & "\users.xls"
Set objWorkbook = objExcel.Workbooks.Open(strFile)
objWorkbook.Activate
objExcel.Visible = False
intRow = 2 ' starts reading file at line 2
' this part runs a loop through the excel file reading each userid and getting data requested.
' ---------------------------------------------------------------------------------------------
Do Until objExcel.Cells(intRow,1).Value = ""
ExcelRow = objExcel.Cells(intRow, 1)
Call GetOU ' calling sub to search
intRow = intRow + 1
Loop
' This section just formats the excel file to widen the columns
' --------------------------------------------------------------
Set objRange = objExcel.Range("A1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("B1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("C1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("D1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
objExcel.ActiveWorkbook.Save
objExcel.Quit
' Sub to get Details for user
' ----------------------------
Sub GetOU
On Error Resume Next
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand = CreateObject("ADODB.Command")
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Size Limit") = 100000
objCommand.Properties("Searchscope") = 2
objCommand.CommandText = "SELECT distinguishedName FROM 'LDAP://" & _
strDomain & _
"' WHERE objectCategory='User' AND DisplayName = '" & _
ExcelRow & "'"
Set objRecordSet = objCommand.Execute
If Not objRecordSet.EOF Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
' This is where the script does 'its thing' ...
' gets what you want.
' ------------------------------------------------
Set MyUser = GetObject ("LDAP://" & strDN)
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
' ###########################################################
' ###########################################################
Else
Wscript.Echo "User Not Found: " & ExcelRow
End If
Err.Clear
End Sub
If multiple accounts are found, the Record Set will have multiple records and you'll need to loop through it. Your code currently only gets the first item in the Record Set.
Change If Not objRecordSet.EOF Then to Do While Not objRecordSet.EOF
Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
Set MyUser = GetObject ("LDAP://" & strDN)
When inserting the users into the spreadsheet, you'll want to control the placement of the cell dynamically so the same cell isn't written over at each loop.
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
At the end of processing this user, you'll use this to move to the next object (user) in the Record Set
objRecordSet.MoveNext
Then instead of End If, you'll use Loop
EDIT:
Also, instead of connecting to the object using Set MyUser = GetObject(etc), could you just use "SELECT sAMAccountName FROM... in your query then strsAMAccountName = objRecordSet.Fields("sAMAccountName") to save some memory/time?
Edit2:
I am doing this in my script.
If objRecordSet.RecordCount = 0 Then
'Things to do if not found
Exit Sub 'Then exit before entering loop
End If
Also, if the user isn't found then objRecordSet.EOF will equal True.

String filter andset permission using VB script

Please help me with 2 things.
I.
When execute this script, Folders are creating like this eg : "CN=Astra,OU=aaa,OU=bbb,OU=ccc,DC=ddd,DC=com"
but I need to create folder with Astra (CN) only.
Code:
On Error Resume Next
Dim objFSO, objFolder
Set objGroup = GetObject _
("LDAP://cn=UserCreation,ou=aaa,ou=bbb,ou=ccc,dc=ddd,dc=com")
objGroup.GetInfo
arrMemberOf = objGroup.GetEx("member")
For Each strMember in arrMemberOf
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder(strMember)
Next
II. Please help me to set user permission to respective folders.
Users are getting from AD group.
Thanks!
sFilterString = "CN=Astra,OU=aaa,OU=bbb,OU=ccc,DC=ddd,DC=com"
'here we break the string into an array of values:
' aJustCN(0) = "CN=Astra"
' aJustCN(1) = "OU=aaa"
' aJustCN(2) = "OU=bbb"
' ...
' aJustCN(5) = "OU=com"
aJustCN = Split(sFilterString)
'Here we just truncate the CN= from the string
sJustCN = Replace(aJustCN(0),"CN=","")
'This will return "Astra"
Wscript.Echo sJustCN

Active Directory PSO fine grained passwords msDS-MaximumPasswordAge

Looking how to create a vbscript to pull the maximum number of days a PSO policy has set. It comes back as a value of ... and I do not know how to get the real value that was set.
This is what I have so far:
Option Explicit
Const ADS_UF_PASSWD_CANT_CHANGE = &H40
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000
Dim strFilePath, objFSO, objFile, adoConnection, adoCommand, objCDOConf
Dim objRootDSE, strDNSDomain, strFilter, strQuery, adoRecordset, objMaxPwdAge
Dim strDN, objShell, lngBiasKey, lngBias, blnPwdExpire, strDept, strAdd
Dim objDate, dtmPwdLastSet, lngFlag, k, address, objAdd, objMessage
' Check for required arguments.
If (Wscript.Arguments.Count < 1) Then
Wscript.Echo "Arguments <FileName> required. For example:" & vbCrLf _
& "cscript PwdLastChanged.vbs c:\MyFolder\UserList.txt"
Wscript.Quit(0)
End If
strFilePath = Wscript.Arguments(0)
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the file for write access.
On Error Resume Next
Set objFile = objFSO.OpenTextFile(strFilePath, 2, True, 0)
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "File " & strFilePath & " cannot be opened"
Wscript.Quit(1)
End If
On Error GoTo 0
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
& "TimeZoneInformation\ActiveTimeBias")
If (UCase(TypeName(lngBiasKey)) = "LONG") Then
lngBias = lngBiasKey
ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
lngBias = 0
For k = 0 To UBound(lngBiasKey)
lngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If
' Use ADO to search the domain for all users.
Set adoConnection = CreateObject("ADODB.Connection")
Set adoCommand = CreateObject("ADODB.Command")
adoConnection.Provider = "ADsDSOOBject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
' Determine the DNS domain from the RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
' Filter to retrieve all user objects.
strFilter = "(&(objectClass=msDS-PasswordSettings))"
' Filter to retrieve all computer objects.
strQuery = "<LDAP://CN=PSO-Information Systems,CN=Password Settings Container,CN=System,DC=yrmc,DC=org>;" _
& ";cn,msDS-LockoutDuration,msDS-MaximumPasswordAge,msDS-
PasswordSettingsPrecedence;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
Do Until adoRecordset.EOF
objFile.WriteLine adoRecordset.Fields("cn").Value
adoRecordset.MoveNext
Loop
adoRecordset.Close
I can get a value for cn and even msDS-PasswordSettingsPrecedence but not for msDS-MaximumPasswordAge. Any help would be appreciated.
This is at best a partial answer but I did some searching and I believe you will need one or more of the following:
DSGet/DSQuery
LDIFDE to manage PSO's.
Quest's "Free PowerShell Commands for Active Directory"
Using Quest's free tools, you might find this link handy
Put square brackets around our Active Directory attribute name:
See the blog post "How can I retrieve the value of an active directory attribute that has a hyphen in its name" for more.
you have to find UsersPSO location in your AD like that
domainLookupString = ""CN=UsersPSO,CN=Password Settings Container,CN=System,DC=COMPAY,DC=ORG";
then run the ldap query
ldapFilterString = "(&(objectClass=msDS-PasswordSettings))";
at the end, get the ldap attribute with the Maximum Password Age of the current PSO policy
"msDS-MaximumPasswordAge"

Resources