Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # VARIABLES
- $logFile = "C:\temp\Baseline_DisconnectedSessions.csv"
- $sessions = $null
- # DATATABLE
- $sessionsTable = New-Object System.Data.DataTable("Sessions")
- # DataTable "Sessions" Schema (columns)
- $stringCols = @("USERNAME","ID","STATE","IDLETIME","LOGONTIME","FlagLOGOFF","LOGOFFSUCCESS","TimeStamp")
- foreach ($col in $stringCols) {[void]$sessionsTable.Columns.Add($col,"string")} # These columns are type=string
- # START MAIN
- $sessions = (query user 2>&1 | ForEach-Object{ "$_" }) # Get user session info and suppress nativecommand errors
- foreach ($sesh in $sessions){
- $trimmedSession = (($sesh -replace '^>', '') -replace '\s{2,}', ',').Trim() # Clean up the string
- if ($trimmedSession.Split(',').Count -eq 5) {
- # if the string is split into 5 chunks by commas do the following work
- ($trimmedSession -replace '(^[^,]+)', '$1,') | Out-Null
- $row = $sessionsTable.NewRow()
- $row.USERNAME,$row.ID,$row.STATE,$row.IDLETIME,$row.LOGONTIME = $trimmedSession.split(',') # Chunk up the string and set each chunk to the appropriate field in the table
- if (($row.IDLETIME -gt "0+00:40") -AND ($row.State -eq "Disc")){
- $row.FlagLOGOFF = $true # if the IDLETIME is greater than 40 minutes and the STATE is DISC set this field to TRUE
- } else {
- $row.FlagLOGOFF = $false # else set this field to FALSE
- }
- $sessionsTable.rows.Add($row)
- } else { CONTINUE } # if the string is not split into 5 chunks by commas move on to next $sesh in the foreach
- }
- $sessions = $sesh = $trimmedSession = $null # nulling out some variables, just in case
- foreach ($row in $sessionsTable){
- if ($row.FlagLOGOFF -eq "TRUE"){
- # read the table, if the field FlagLOGOFF is set to true do the following work
- $dateTime = Get-Date
- $row.TimeStamp = $dateTime # set the TIMESTAMP field to the current date and time
- logoff $row.ID # Log off the user
- if ((query user $row.Username 2>&1 | ForEach-Object{ "$_" }) -like "No User exists for*"){
- $row.LOGOFFSUCCESS = $true # check for the user, if there is no session we succeeded, set the LOGOFFSUCCESS field to TRUE
- } else {
- $row.LOGOFFSUCCESS = $false # check for the user, if there is a session we failed, set the LOGOFFSUCCESS field to FALSE
- }
- $sessionsTable | Export-Csv -NoTypeInformation $logFile # write the table to the log
- Set-Content $logFile ((Get-Content $logFile) -replace '"') # remove quotes from the log because I hate them
- }
- }
- $dateTime = $null # nulling out some variables, just in case
- # END SCRIPT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement