Powershell script to generate csv from event log

Afternoon
Please could I have some assistance writing a script.
The script will output logon/logoff and re-connection events logged in the Terminal Services LocalSessionManager log.
The script is to be scheduled to run 23:59:00 every day using the Windows scheduler.
The results will be outputted to csv file. The csv files will be saved and then used to lookup who has been logging on and off our terminal services server.

The script is to extract event information from the "Microsoft-Windows-TerminalServices-LocalSessionManager" operational logs and should only output event IDs 21,23,24,25 that were logged that day.
The results should be saved to a csv file.
The csv file created must be named "YYYY-MM-DD.csv", where the letters represent the current date.
The csv file must be saved within a directory named MM, where MM represents the current month.
The MM directory is located within a directory named YYYY, where YYYY represents the current year.
The YYYY directory is located within the same directory that the powershell script is being executed from.
If any directories do not exist, they must be created by the script prior to the script being saved (This avoids any invalid file path errors)

I have attached the script code I already have, however this outputs ALL events.
I need assistance limiting the results to just event ids 21,23,24 and 25 and events logged on the day the script is being executed and saving to the correct folder as mentioned above.

$LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
$Results = @()
$Events = Get-WinEvent -LogName $LogName
foreach ($Event in $Events) {
    $EventXml = [xml]$Event.ToXML()

    $ResultHash = @{
        Time        = $Event.TimeCreated.ToString()
        'Event ID'  = $Event.Id
        'Desc'      = ($Event.Message -split "`n")[0]
        Username    = $EventXml.Event.UserData.EventXML.User
        'Source IP' = $EventXml.Event.UserData.EventXML.Address
        'Details'   = $Event.Message
    }

    $Results += (New-Object PSObject -Property $ResultHash)
}

$Results | Export-Csv 'Remote Desktop Users.csv'

Open in new window


Many thanks in advance!
antoniokingAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Will this work?
$LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
$checkDate = (Get-Date).AddDays(-1).Date
Get-WinEvent -LogName $LogName | ? {($_.id -eq 21 -or $_.id -eq 23 -or $_.id -eq 24 -or $_.id -eq 25) -and $_.TimeCreated.Date -eq $checkDate} | Export-Csv 'Remote Desktop Users.csv'

Open in new window

0
antoniokingAuthor Commented:
Thanks I'll test this out tomorrow when I'm back in my office.
One thing I do notice though is it doesn't cover the requirement of saving the file with the naming structure mentioned in my question.
0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
That can easily be written. I'll see if I get a few seconds later today.
0
What were the top attacks of Q1 2018?

The Threat Lab team analyzes data from WatchGuard’s Firebox Feed, internal and partner threat intelligence, and a research honeynet, to provide insightful analysis about the top threats on the Internet. Check out our Q1 2018 report for smart, practical security advice today!

Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Here's with the folder checks and naming conventions:
$LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
$checkDate = (Get-Date).AddDays(-1).Date
$WorkingDate = Get-Date
$filename = $WorkingDate.ToString('yyyy-MM-dd')+'.csv'
$YearDir = $PSScriptRoot+'\'+$WorkingDate.ToString('yyyy')
$MonthDir = $YearDir+'\'+$WorkingDate.ToString('MM')
$OutputFile = $MonthDir+'\'+$filename
If(!(Test-Path $YearDir)){New-Item $YearDir -ItemType Directory}
If(!(Test-Path $MonthDir)){New-Item $MonthDir -ItemType Directory}

Get-WinEvent -LogName $LogName | ? {($_.id -eq 21 -or $_.id -eq 23 -or $_.id -eq 24 -or $_.id -eq 25) -and $_.TimeCreated.Date -eq $checkDate} | Export-Csv $OutputFile

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
antoniokingAuthor Commented:
Many thanks for this, works great.

I edited the code slightly so the csv only contains the columns I need.

$LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
$Results = @()
$checkDate = (Get-Date).AddDays(-1).Date
$WorkingDate = Get-Date
$filename = $WorkingDate.ToString('yyyy-MM-dd')+'.csv'
$YearDir = $PSScriptRoot+'\'+$WorkingDate.ToString('yyyy')
$MonthDir = $YearDir+'\'+$WorkingDate.ToString('MMMM')
$OutputFile = $MonthDir+'\'+$filename
If(!(Test-Path $YearDir)){New-Item $YearDir -ItemType Directory}
If(!(Test-Path $MonthDir)){New-Item $MonthDir -ItemType Directory}
$Events = Get-WinEvent -LogName $LogName | ? {($_.id -eq 21 -or $_.id -eq 23 -or $_.id -eq 24 -or $_.id -eq 25) -and $_.TimeCreated.Date -eq $checkDate} 
foreach ($Event in $Events) {
    $EventXml = [xml]$Event.ToXML()

    $ResultHash = @{
        Time        = $Event.TimeCreated.ToString()
        'Event ID'  = $Event.Id
        'Desc'      = ($Event.Message -split "`n")[0]
        Username    = $EventXml.Event.UserData.EventXML.User
        'Source IP' = $EventXml.Event.UserData.EventXML.Address
        'Details'   = $Event.Message
    }

    $Results += (New-Object PSObject -Property $ResultHash)
}
$Results | Export-Csv $OutputFile

Open in new window

0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Excellent! Glad to help!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.