Pages

Wednesday, February 9, 2011

Get Last logon of user in AD

Simple powershell script to display last logon of all users.



$searcher = New-Object DirectoryServices.DirectorySearcher([adsi]"")
$searcher.filter = "(objectclass=user)"
$users = $searcher.findall()

Foreach($user in $users)
{
if($user.properties.item("lastLogon") -ne 0)
{
$a = [datetime]::FromFileTime([int64]::Parse($user.properties.item("lastLogon")))
"$($user.properties.item(`"name`")) $a"
}
}

List all member of a group in AD

Simple VB script to display members of a group.


Copy the below code and edit as ur requirement and save it as extension .vbs

On Error Resume Next

Set objGroup = GetObject _
("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
objGroup.GetInfo

arrMemberOf = objGroup.GetEx("member")

WScript.Echo "Members:"
For Each strMember in arrMemberOf
WScript.echo strMember
Next

How to get last login time for Active Directory users

Copy the below code and save it as .vbs extension on desktop. You should change the second line, need to type your domain name

On Error Resume Next
sEnterDCs = "your domain name"
sObjects = Split(sEnterDCs, ",")
Set oDomain = GetObject("WinNT://" & sObjects(0))
oDomain.Filter = Array("User")
WScript.Echo "Showing last login times of accounts from: " & oDomain.Name & vbNewLine
For Each oDomainItem In oDomain
sUsrLogin = oDomainItem.LastLogin
If UBound(sObjects) >= 1 Then
For ii = 1 To UBound(sObjects)
Set oUsr = GetObject("WinNT://" & sObjects(ii) & "/" & oDomainItem.Name & ",user")
If oUsr.LastLogin > sUsrLogin Then sUsrLogin = oUsr.LastLogin
Next
End If
WScript.Echo "Username: " & Left(oDomainItem.Name & Space(22),22) & "Last login: " & FormatDateTime(sUsrLogin)
Next

Final Step :-

Now your script file in desktop with the extension of .vbs . Then go to the command prompt

C:\Documents and settings\userprofile\Desktop\>cscript savedscript.vbs > log.xls