Disconnected Session Report

# Purpose of the Script:
# Import the Active Directory module for the Get-ADComputer CmdLet
Import-Module ActiveDirectory
# Get today's date for the report
$today = Get-Date

# Setup email parameters  to send the report in email (Note:Some email will not alloe larger attachments )
$subject = "User Account Disconnected SERVER SESSIONS REPORT - " + $today
$priority = "Normal"
$smtpServer = "<SMTP Server Address>"
$emailFrom = "<Canbe anything, from address where the report is generated, usually ServerName@Report.com>"
$emailTo = "<To Email Address>"
$report = "\\<LocalPath to save the generated report>($(Get-Date -Format yyyy-MM-dd)).csv"

Function Get-LoggedOnUsers
{
    [CmdletBinding()]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$False,
                   ValueFromPipeline=$true,
                   Position=0)]
        [Alias( 'HostName','ComputerName','ServerName','Name' )]
        $Server = $env:COMPUTERNAME
    )
    Begin
    {
        if($server -eq $null)
        {
        $server = "$ENV:COMPUTERNAME"
        }
        $users = @()
    }
    Process
    {
        ForEach ($Entry in $Server)
        {
            # Query using quser, 2>$null to hide "No users exists...", then skip to the next server
            $quser = quser /server:$Entry 2>$null
            if(!($quser)){
                Continue
            }
            #Remove column headers
            $quser = $quser[1..$($quser.Count)]
            foreach($user in $quser)
            {
                $usersObj = [PSCustomObject]@{Server       = $null
                                              Username     = $null
                                              SessionName  = $null
                                              SessionId    = $Null
                                              SessionState = $null
                                              LogonTime    = $null
                                              IdleTime     = $null
                }
                $quserData = $user -split "\s+"
                #We have to splice the array if the session is disconnected (as the SESSIONNAME column quserData[2] is empty)
                if(($user | select-string "Disc") -ne $null)
                {
                    #User is disconnected
                    $quserData = ($quserData[0..1],"null",$quserData[2..($quserData.Length -1)]) -split "\s+"
                }
                $usersObj.Server = $server
                $usersObj.Username = $quserData[1]
                $usersObj.SessionName = $quserData[2]
                $usersObj.SessionID = $quserData[3]
                $usersObj.SessionState = $quserData[4]
                # IdleTime
                $quserData[5] = $quserData[5] -replace "\+",":" -replace "\.","0:0" -replace "Disc","0:0"
                if($quserData[5] -like "*:*")
                {
                    $usersObj.IdleTime = [timespan]"$($quserData[5])"
                }
                elseif($quserData[5] -eq "." -or $quserData[5] -eq "none")
                {
                    $usersObj.idleTime = [timespan]"0:0"
                }
                else
                {
                    $usersObj.IdleTime = [timespan]"0:$($quserData[5])"
                }
                $usersObj.LogonTime = (Get-Date "$($quserData[6]) $($quserData[7]) $($quserData[8] )")
                $users += $usersObj
                }
            Write-Output $users
        }
    }
    End
    {
    }
}
$log = @()
$path = "<\\SharePath to save the file\FileName>.txt"
$ServerList = Get-Content -Path $Path
foreach ($server in $ServerList) {
$Server | Get-LoggedOnUsers | Where-Object {($_.UserName -like "*") -and ($_.SessionState -like "DISC") } | ForEach-Object {
    $Log += Write-Output $_
#    Uncomment the below cmd to logoff the disconnected sessions in parlell
#    Invoke-Expression -Command $("LOGOFF " + $_.SessionID + " /server:” + $_.Server)   
}
$Log | Export-Csv -Path "<Share File Path Location>($(Get-Date -Format yyyy-MM-dd)).csv" -NoTypeInformation
}

# Send the report email
Send-MailMessage -To $emailTo -Subject $subject -Body $Report -SmtpServer $smtpServer -From $emailFrom -Priority $priority

No comments:

Post a Comment