Filter EventLog based on date - powershell

I am trying to pull out some information from the eventlog through PowerShell based on the date today.
So far I have the code below:
$today = (Get-Date).ToString("dd/MM/yyyy")
Get-EventLog Security | where {$_.EventID -eq 4624} | where {$_.TimeGenerated -eq $today}
Now I have printed the result of today and can confirm that the outputted date is 04/12/2017, I have also printed the date of the TimeGenerated attriubute from the EventID object and that also shows the date in the same format.
Any ideas on where I am going wrong?

The TimeGenerated property holds a DateTime value, not a string, so don't compare it to a date string. Also, you should filter via Get-EventLog parameters whenever possible, because that filtering happens at the source. This is particularly relevant when querying remote eventlogs to reduce the amount of data that is transmitted over the network.
$today = (Get-Date).Date
$tomorrow = $today.AddDays(1)
Get-EventLog -LogName Security -InstanceId 4626 -After $today -Before $tomorrow

Related

Trying to export tickets/incidents from SCSM to csv file using powershell

I am trying to do a simple ticket/incident file export using PowerShell. All of our tickets go into the Service manager 2019 Console.
What I am trying to do is be able to filter and export our tickets using certain date range. Our senior system engineer was able to help me get started and I am trying to figure out the best way to do this. So this is what he sent me:
____________________________________________
you always want to filter / where as far left as possible to reduce processing overhead
also Tab is your friend when typing cmdlets - usually something like
Get-SCSMIncident -<Tab>
and it will show you your options
or Get-SCSMIncident -Help
you can also use Where-Object to filter once you have the correct subitems
Get-SCSMIncident | Where-Object {$_.Status -eq "Active"}
because you're doing the filter AFTER Get-SCSMIncident, it's going to find ALL incidents in the background, THEN filter them (slow/bad)
____________________________________________
So I tried a few things. He suggested to do the following below, create variables, store them and pull the data later.
$allincidents = Get-SCSMIncident
$resolved = $allincdients | Where-Object {$_.Status -eq "Resolved"}
$active = $allincdients | Where-Object {$_.Status -eq "Active"
Then I would export the info such as below to a csv file
$active | export-csv c:\temp\scsm_incidents.csv -nti
The issue is that when I execute it, the initial storing of the variables it is taking too long, because we have obviously thousands and thousands of tickets.
I then thought what if I did the following below
Create the date variables first and store them.
$startDate = Get-Date -Year 2022 -Month 1 -Day 1
$endDate = Get-Date -Year 2022 -Month 2 -Day 2
Get-SCSMIncident | Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} | Export-Csv C:\Temp\SCSM-tickets.csv -nti
And given the logic that my Senior Engineer told me, it is going through all the tickets first because of the Get-SCSMIncident and then filtering and then storing into an csv file.
So my question is there a way to sort of go backwards? I know computer language wise it wouldn't make sense because it doesn't know what object it is being pointed to.
Like for example
Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} | Get-SCSMIncident | Export-Csv C:\Temp\SCSM-tickets.csv -nti
The end result is that I want to be able to pull data on a weekly basis using just a date range, without have to run through all the tickets every time. Since new tickets are being generated everyday, each time I run through it, it will take longer and longer and longer. I am by no means expert with powershell at all and looking for any insight on export data files much simpler or faster. If anyone has any ideas I would greatly appreciate it.
FYI I know I can pull each ticket at a time, our naming scheme used is INC##### so for example to pull any ticket
Get-SCSMIncident -id "INC10105"
This would pull up this one ticket in powershell.
I don't know all the powershell commands and searching through the library is confusing
If anyone knows a way of how to do something like this pulling tickets in sets that would be helpful.
Get-SCSMIncident -id "INC00001" TO -id "INC00500" | Export-Csv C:\Temp\SCSM-tickets.csv -nti
Or evening pulling data by date.
Apologize for the super long post. Also if anyone knows how to export tickets in Service Manager Console please let me know too!!! I searched everywhere and seems like I can't export anything
As stated in my comments, unless the cmdlet Get-SCSMIncident has filtering by DateTime range capabilities, it is unlikely that there is a way around having to go through all the collection, however, there are ways the code could be improved so it can do the filtering faster. A foreach loop (enumeration) loop in addition to an if condition (filtering condition) is much faster than Where-Object.
$startDate = Get-Date -Year 2022 -Month 1 -Day 1
$endDate = Get-Date -Year 2022 -Month 2 -Day 2
$incs = foreach($inc in Get-SCSMIncident)
{
if($inc.CreatedDate -gt $endDate -or $inc.CreatedDate -lt $startDate)
{
# If the Incident's CreatedDate is greater than `$endDate` OR
# lower than `$startDate` go to the next Incident.
# In other words, skip this Incident.
continue
}
[pscustomobjct]#{
ID = $inc.ID
Status = $inc.Status
Title = $inc.Title
Description = $inc.Description -replace '\r?\n', ' '
AffectedUser = $inc.AffectedUser
AssignedTo = $inc.AssignedTo
CreatedDate = $inc.CreatedDate
TierQueue = $inc.TierQueue
Urgency = $inc.Urgency
Priority = $inc.Properity
}
}
$incs | Export-Csv path/to/exported.csv -NoTypeInformation

Get Date and Time of Specific Event Viewer Source

Attempting to get the Date and Time of Source Winlogon from EventViewer for timing purposes and this is what I currently have. I'm not the best at Powershell scripting but hopefully I was close enough to it's a simple fix. Please help! I've also referenced this, but it didn't help to my prevail.
$LogSettingsEvent = "Winlogin"
$refDate = (Get-Date).Adddays(0)
Get-WinEvent $LogSettingsEvent -InformationAction | Where-Object
{$_.LastWriteTime -gt $refDate}
The best way I have found to filter event logs is using `-FilterHastable'
Example (5 days of logs):
$LogSettingsEvent = "WinLogs"
[hashtable]$filter =#{}
$filter.Add('LogName', $LogSettingsEvent)
#add start time (5 days ago)
$start = (Get-Date).AddDays(-5)
#must have an endtime with start time (make it today)
$end = Get-Date
#Get the logs:
$systemLogs = Get-WinEvent -FilterHashtable $filter
#display it
$systemLogs

Where "AND" not functioning as expected

I am pulling Windows event logs using Get-EventLog and removing log events I don't want to see using source and eventid as criteria. When I do parse using where, the values are note respected. For example if I do
$Events = Get-EventLog -ComputerName $computer -LogName Application
$events | ft source, eventid
I see the following:
Source EventID
------ -------
AutoEnrollment 34
If I do:
$events |
?{($_.Source -ne "AutoEnrollment" -and $_.EventID -ne 14)} |
ft source, eventid
The results are empty, which puzzles me because clearly the eventid does not match. I expect if I were evaluating against $_.eventid -ne 34, then the results would not show that event. This worked when I wrote the code on PowerShell 2 back in 2012. Now on v5.1 it fails to properly evaluate.
Has something changed that I should be aware of, or did I screw it up initially? If I AM doing this wrong, any suggestions on how to say "where event not match specified criteria as a set" so that source=autoenrollment and eventid=34 will show up, but events with source=autoenrollment and eventid=14 will not.
These two posts by mjsqu answered the question:
es, and #MathiasR.Jessen suggestion is right. NOT(A AND B) is not the same as NOT(A) AND NOT(B), it's equivalent to NOT(A) OR NOT(B). Why this used to work on PS2 is odd. – mjsqu 21 hours ago
I would rewrite as
... |? {-not ($_.Source -eq "AutoEnrollment" -and $_.EventID -eq 14)}
... which is arguably more human-readable.

In Powershell, how do I input <datetime>?

For example, if I am trying to retrieve eventlog before a specific date and time.
Get-EventLog system -Before (what do I enter here?)
Essentially, what on earth is the format for entering datetimes?
Try it this way:
Get-EventLog System -Before "2/22/2017 7:00am"
According to the docs https://msdn.microsoft.com/powershell/reference/4.0/microsoft.powershell.management/Get-EventLog
-Before requires a type of DateTime
You need to use that. Simple as that.
There are many ways to satisfy this in powershell. Here is one example which can be used for the -Before parameter and another for the -After which takes the same type
$dt = Get-Date
Get-EventLog system -Before $dt -after "2/15/2017 8:27:50 PM" -LogName System

Retrieve wrong DateTime

I'm using this code below to retrieve the value for the TimeGenerated on a win32 event log on a remote server.
$event = Get-WMIObject -ComputerName $server -Query "SELECT * FROM Win32_NTLogEvent WHERE LogFile='Application' AND CategoryString = 'Server Startup'" |
Select -ExpandProperty TimeGenerated -First 1
The return value is:
20160123155933.000000-000
but the event log via the event viewer shows this as the value:
Logged: 1/23/2016 10:59:33 AM
How would I extract the correct date in the format above?
As an aside, if you run your command in the ISE, you can discover properties and commands on the objects returned using IntelliSense.
That said, this article talks a lot about "eventlog" and "TimeGenerated" (the 2 terms I searched on the find this answer).
Don't use -ExpandProperty, but rather call ConvertToDateTime() something similar to what I show below (I modified your call to just grab the first event in my log).
$obj = Get-WMIObject -Query "SELECT * FROM Win32_NTLogEvent WHERE LogFile='Application'" | Select -First 1
$obj.ConvertToDateTime($obj.TimeGenerated).ToString()
This outputs a formatted date converted from raw UTC to local time.
TimeGenerated : 20160124010615.134877-000
becomes
1/23/2016 5:06:15 PM
I think with this info, you have a workable solution to build upon.