...hopefully some useful VMware related stuff

Script to identify Inactive Active Directory User Accounts for an AD 2003 domain

06/07/2010 21:00

Get all Active Directory users in the domain, pick out firstly User accounts which have never logged in and second get the last logged in time for each account which have logged in and report back any accounts which haven't logged in within the last 31 days.

Couldn't find PowerShell cmdlets for Active Directory 2003 and didn't want to install anything more than PowerShell on the servers, so I used a combination of standard tools 'dsget', 'dsquery' and also a VB script from https://www.rlmueller.net/Last%20Logon.htm

I created a couple of functions, first to strip the CN name from a Distinguished Name and second to get the domain name from the distinguished name so I could run this at multiple domains and yet the report could be distinguished by the domain name.

I also used a couple of functions to strip out a regex from the original CSV file from https://www.huddledmasses.org

 

The result is two email reports:

 

User accounts which have Never logged in:

User accounts which haven't logged in within the last 31 days:

 

Download the script HERE and is included below:

 

# Active Directory User Logon Statistics Email Report (AD 2003+)
# https://www.a2-alpha.co.uk
# Requires: dsget, dsquery, lastlogon.vbs (https://www.rlmueller.net/Last%20Logon.htm)
# lastlogon.vbs should be in the root of C:\ or update the script!
# Uses some import functions from: https://huddledmasses.org/powershell-convert-delimiters-import-tab-delimited-text/
# Version 1.0 - Original Script
# Version 1.1 - Added Time Status
# Version 1.2 - Added Error Checking
# 20100706
# Current Version 1.2
# Feedback to dan@a2-alpha.co.uk would be great!

##################################################

# PREREQUISITES

# Requires: dsget, dsquery, lastlogon.vbs (https://www.rlmueller.net/Last%20Logon.htm)
# lastlogon.vbs should be in the root of C:\ or update the script!
# Uses some import functions from: https://huddledmasses.org/powershell-convert-delimiters-import-tab-delimited-text/

##################################################

# DESCRIPTION

# Queries Active Directory for all users last logon time using the lastlogon.vbs script.
# This is then imported into a PowerShell variable
# Each user is queried using dsquery and dsget for their display name
# Two emails result, the first a list of users who have never logged in and
# a list of all users who have not logged in during the period specified (31 days at the moment)
# whos accounts are enabled.
# Use this script to check this information and disable any unused user accounts for security of the environment.

##################################################

# VARIABLES

$recipient = "user@domain.com"
$sender = "reporting@domain.com"
$smtpserver = "EXCHANGE01"
$daystocheck = 31

##################################################

$ErrorActionPreference = "SilentlyContinue"
$Error.Clear()
dsquery > c:\temp.txt
If($Error -like "*dsquery*")
{
    Clear
    ""
    "dsquery was not found on this machine, please check you are running this on a domain member server"
    ""
}
Else
{
    $Error.Clear()
    dsget > c:\temp.txt
    If($Error -like "*dsget*")
    {
        Clear
        ""
        "dsget was not found on this machine, please check you are running this on a domain member server"
        ""
    }
    Else
    {
        $Error.Clear()
        if(!(test-path -path "C:\LastLogon.vbs"))
        {
        Clear
        ""
        "The LastLogon.vbs Script was not in the default location, please check (C:\LastLogon.vbs)"
        ""
        }
        Else
        {
        Clear
        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Prerequisites optimal"

        ##################################################

        # FUNCTIONS

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Loading Functions"

        Function Convert-Delimiter([regex]$from,[string]$to)
        {
          process
          {
            $_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:((?:.(?!$from))*.)(?:$from|`$))","Þ`$1`$2Þ$to"
            $_ = $_ -replace "Þ(?:$to|Þ)?`$","Þ"
            $_ = $_ -replace "`"`"","`"" -replace "`"","`"`""
            $_ = $_ -replace "Þ((?:[^Þ`"](?!$to))+)Þ($to|`$)","`$1`$2"
            $_ = $_ -replace "Þ","`"" -replace "Þ","`""
            $_
          }
        }

        Function Import-Delimited([regex]$delimiter=",", [string]$PsPath="")
        {
          begin{
            $script:tmp = [IO.Path]::GetTempFileName()
            write-debug "Using tempfile $($script:tmp)"
           
            Function Import-String([string]$inputString){
              if($inputString.Length -gt 0 ) {
              write-debug "Importing $inputString"
              if(($inputString -as [IO.FileInfo]).Exists) {
                Get-Content $inputString | Convert-Delimiter $delimiter "," | Add-Content $script:tmp
              } elseif( ((Join-Path $pwd $inputString) -as [IO.FileInfo]).Exists) {
                Get-Content (Join-Path $pwd $inputString) | Convert-Delimiter $delimiter "," | Add-Content $script:tmp
              } else {
                $inputString | Convert-Delimiter  $delimiter "," | Add-Content $script:tmp
              }
              } else {
                write-debug "Nothing to Import"
              }
            }
           
            Import-String $PsPath
          }
         
          process{
            Import-String $_
          }
          end
          {
            Import-Csv $script:tmp
          }
        }

        Function Get-CName([string]$DistName)
        # Convert Distinguished name to CN
        # https://www.a2-alpha.co.uk
        # 20100705
        {
          process
          {
            $_ = $DistName.Split(",")
            $_ = $_[0]
            $_.Substring(3)
          }
        }

        function Get-DC([string]$DistName)
        # Get Domain from Distinguished Name
        # https://www.a2-alpha.co.uk
        # 20100705
        {
            Process
            {
                $_ = $DistName.Split(",")
                $Count = 0
                ForEach($line in $_)
                {
                    If($line -like "*DC*")
                    {
                        $Count++
                    }
                }
                $LineTotal = $_.Count
                If($Count -gt 3)
                {
                    "Unable to Determine Domain"
                }
                ElseIf($Count -eq 3)
                {
                    $LastLine = ($_.Count)-1
                    $LastLine1 = ($_.Count)-2
                    $LastLine2 = ($_.Count)-3
                    $D1 = ($_[$LastLine]).Substring(3)
                    $D2 = ($_[$LastLine1]).Substring(3)
                    $D3 = ($_[$LastLine2]).Substring(3)
                    "$D3.$D2.$D1"
                }
                ElseIf($Count -eq 2)
                {
                    $LastLine = ($_.Count)-1
                    $LastLine1 = ($_.Count)-2
                    $D1 = ($_[$LastLine]).Substring(3)
                    $D2 = ($_[$LastLine1]).Substring(3)
                    "$D2.$D1"
                }
                Else
                {
                    "Unable to Determine Domain"
                }
            }
        }


        ##################################################

        # CREATING THE USER OBJECT AND INTERPRETING DATA

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Importing AD User Data"

        $userdata = @()
        echo "Name;LastLogon" > c:\lastlogontemp.csv
        cscript //nologo c:\LastLogon.vbs >> c:\lastlogontemp.csv
        Get-content c:\lastlogontemp.csv | convert-delimiter ";" "," | set-content c:\lastlogon.csv
        $userdata += import-csv c:\lastlogon.csv
        $never = $userdata | select Name, LastLogon | where {$_.LastLogon -like "Never"}

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Building First User Object"

        $NeverRep = @()
        ForEach($usrNev in $never)
        {
            $NeverObj = "" | Select Name, LastLogon, DisplayName
            $NeverObj.Name = $usrNev.Name
            $NeverObj.LastLogon = $usrNev.LastLogon
            $NeverObj.DisplayName = Get-CName $usrNev.Name
            $NeverRep += $NeverObj
        }
        $loggedinusers = @()
        $loggedin = $userdata | select Name, LastLogon | where {$_.LastLogon -notlike "Never"}

        $DomainbeingChecked = Get-DC (($loggedin[0]).Name)

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Building Second User Object"

        ForEach($user in $loggedin)
        {
            $disabled = dsget user $user.Name -disabled
            $loggedinObj = "" | select Name, LastLogon, DisplayName, Disabled, "Last $daystocheck Days"
            $loggedinObj.Name = $user.Name
            [datetime]$lastlogon = (get-date -UFormat "%m/%d/%Y %T"($user.LastLogon))
            $loggedinObj.LastLogon = $lastlogon
            $loggedinObj.DisplayName = Get-CName $user.Name
            If($disabled -like "*no*")
            {
                $loggedinObj.Disabled = "No"
            }
            Else
            {
                $loggedinObj.Disabled = "Yes"
            }
            $loggedinUsers += $loggedinObj
           
            [datetime]$checkdate = (get-date((get-date).AddDays(-$daystocheck)))
           
            If($loggedinObj.LastLogon -gt ($checkdate))
            {
                $loggedinObj."Last $daystocheck Days" = "Yes"
            }
            Else
            {
                $loggedinObj."Last $daystocheck Days" = "No"
            }
        }

        ##################################################

        # REPORTING

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Creating Report"

        $loggedinUsers = $loggedinUsers
        $report = $loggedinUsers | sort LastLogon | select DisplayName, "Last $daystocheck Days", LastLogon, Disabled | where {$_."Last $daystocheck Days" -like "No" -and $_.Disabled -like "No"}

        ##################################################

        # EMAILING

        $body = $report | ft -AutoSize

        if(!$body)
        {
            $body = "No Data to Report"
        }

        $body = $body | out-string

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Emailing to $recipient"

        Send-MailMessage -to "$recipient" -From "$sender" -Subject "$DomainbeingChecked - Inactive Users" -SmtpServer "$smtpserver" -Body $body

        $Never = $NeverRep | Select DisplayName, LastLogon | Out-String

        Send-MailMessage -to "$recipient" -From "$sender" -Subject "$DomainbeingChecked - Users Never Logged In" -SmtpServer "$smtpserver" -Body $Never

        ##################################################

        # TIDY UP TEMP FILES

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Deleting Temp Files"

        Remove-Item c:\lastlogontemp.csv
        Remove-Item c:\lastlogon.csv
        Remove-Item c:\temp.txt

        ##################################################

        # END OF SCRIPT

        $currenttime = get-date -UFormat "%T"
        "$currenttime ... Script Ends"

        ##################################################
        }
    }
}

 

Script to identify Inactive Active Directory User Accounts for an AD 2003 domain

Date: 21/05/2023

By: LorenzoWhace

Subject: test

sdfdgreteEQ456578tgf=

Date: 21/05/2023

By: Hunter

Subject: test

test@iwdjfnvn1

Date: 16/10/2021

By: Inozemcevrek

Subject: эссе на заказ

https://graph.org/kursovye-na-zakaz-09-29-14 заказать решение контрольной работы


Как сделать заказ?

Для заказа работы вам необходимо зарегистрироваться на нашем сайте. Регистрация займет не более одной минуты, НО взамен вы получите удобный кабинет для мониторинга своих заказов, общения с менеджером/автором.

Как оплатить?

Заказ можно оплатить как онлайн в личном кабинете, так и переводом средств на банковскую карту через платежные терминалы.

Как быстро обработают мою заявку?

Наши операторы находятся онлайн с 9 утра до 18:00, мы стараемся обрабатывать все заявки не более чем за 30 минут. Но в некоторых случаях оценка работы, может занять длительное время.

Вы вносите исправления?

Да, конечно. Мы БЕСПЛАТНО исправляем все замечания согласно задания. ***Мы не вносим бесплатно правки, если после согласования и выполнения работы изменились изначальные условия задания.

Вы выполняете технические дисциплины?

Да, мы выполняем весь спектр технических дисциплин.
https://telegra.ph/zakazat-kursovuyu-rabotu-srochno-09-29-18 заказать контрольную работу


@tele

Date: 14/10/2021

By: Selivantevrek

Subject: курсовые на заказ срочно

https://telegra.ph/otchet-po-praktike-zakazat-09-29-20 написать курсовую работу


ПОБЕЖДАЕМ ЗАЧЕТЫ, СЕССИЮ И ТРУДНЫЕ ПРЕДМЕТЫ
Помощь в выполнении курсовых, дипломных контрольных и многих других работ

Оставь заявку — остальное сделаем мы

- Строго соблюдаем требования методички, знаем все ГОСТы и нормы АНТИПЛАГИАТА
- Все работы проходят проверку качества перед отправкой клиенту, вы гарантировано получите отличный материал
- Ваши деньги в безопасности. В случае несоответствующего выполнения работы мы вернем вам деньги
https://graph.org/reshenie-kontrolnyh-09-29-18 решение задачи по экономике


@tele

Date: 01/07/2021

By: Jameslog

Subject: create what is pbn fast

[url=https://pbnsiteslist51739.p2blogs.com/4950129/5-essential-elements-for-site-not-secured]do it pbn revenue with the best effect[/url]
[url=https://holdenlgaia.daneblogger.com/4975789/5-essential-elements-for-site-not-secured]creature pbn backlinks fast[/url]
[url=https://edgarcaywu.full-design.com/A-Simple-Key-For-site-panel-Unveiled-43233738]creature pbn site to be displayed in the TOP[/url]
[url=https://pbn-site92357.aboutyoublog.com/5428722/site-png-can-be-fun-for-anyone]let's do pbn 2.0 with the best effect[/url]
[url=https://gregorygxndr.activosblog.com/4986457/the-site-plan-examples-diaries]let's do pbn hosting to be displayed in the TOP[/url]


@mmm=

Date: 15/02/2021

By: Gabrielper

Subject: gangbang

https://tited.xyz - vintage
https://xfuckx.xyz - blowjob
https://hentai-x.xyz - spank
https://breasted.xyz - voyeur
https://vaginals.xyz - gangbang
https://xxxcum.xyz - 3some
https://twinkx.xyz - gangbang
https://latins.xyz - lingerie
https://xxxbukake.xyz - suck
https://swingerclub.xyz - voyeur

Date: 17/01/2021

By: Gabrielper

Subject: pantyhose

[url=https://sissysexwife.xyz/]upskirt[/url]

What is one of the best Torrent Site? We are working hard to be the best Sizzling GIFs site on the net! The all-new Aeolus XXX wheels are built on a wider rim with a redesigned form that’s both quicker and extra stable in all circumstances-together with crosswinds. Now you'll be able to run a deeper, more aerodynamic wheel with more confidence than ever. We are sure that everybody can discover beloved pornstar, applicable category, and favourite intercourse clips here. We update about 10-12 brand new HD porn video clips every 24hrs, so make certain to come again tomorrow for more free porn. Way more. We cowl popular and rare niches, and we attempt to make HD XNXX superior for you whether you're a vanilla form of man or a very pervy type of guy. Only the three X letters are written on the 8-page booklet cover and the ravers silhouettes defines themselfs in front of the laser and strobes.

[url=https://sissysexwife.xyz/]fisting[/url]


[url=https://vpmuoec.webpin.com/?gb=1#top]bondage[/url] [url=https://forum-auto.caradisiac.com/topic/469804-oral-contraceptive/]oral contraceptive[/url] 317823a

@GiG993_+

Date: 06/01/2021

By: Gabrielper

Subject: Flirting in your city

https://bit.ly/3pqNrie - Flirting in your city

https://bit.ly/3pn28mx - Flirting in your city

[URL=https://hot-desire.com/T1kMpvjB][IMG]https://i114.fastpic.ru/thumb/2020/1204/ec/4aeaa674b6965f0736cb750b9d1117ec.jpeg[/IMG][/URL]

@=@=@=

Date: 17/12/2020

By: Rodgercjz

Subject: Meet, be inspired, communicate and continue flirting! Follow the link

https://bit.ly/3pqNrie - Dating and sex without obligation in your city

https://bit.ly/3pn28mx - Sex without obligation in your city

[URL=https://hot-desire.com/T1kMpvjB][IMG]https://i114.fastpic.ru/thumb/2020/1204/57/62df9d31881bed1e84e30230f0cd2457.jpeg[/IMG][/URL]

Date: 28/11/2020

By: Gabrielper

Subject: Dating and sex without obligation in your city

https://hot-desire.com/T1kMpvjB - Meet, be inspired, communicate and continue flirting! Follow the link

https://bit.ly/3pn28mx
- Sex without obligation







@@@==

Search site