Functions and Event Logs

Part 1: Login/Logoff records for Windows Events

Unsolved:

Solved:

Processing Event Logs into a Custom Object

We will collect logon/logoff events from the last 14 days, loop through them, and build a custom object with four properties:

  • Time – from TimeGenerated

  • Id – from InstanceId

  • Event – mapped from InstanceId (Logon/Logoff)

  • User – from ReplacementStrings[1]

Verify that events exist:

Create the script:

Part 2: User ID Translation

Find the SID for your user (champuser)

Adding User SID translation to our 14-day log script

Part 3: Turn Script into a Function that takes user input

Hard code the number of days

A) Turn it into a function that takes 1 input and returns results

  • Instead of the code just running as a script, we are going to wrap it in a function block

  • The function will accept a parameter (input)

  • It will return the table instead of just displaying it

B) The input is the number of days

  • Right now the script is hardcoded to -14 days

  • Instead, we will make this flexible so we can specify any number of days when we call the function

  • Example: You could ask for 7 days, 30 days, etc.

C) Call your function and print results

  • After defining the function, we will use it by calling it with a number

  • Then display what it returns

Allow users to input the number of days

Part 4: Computer start-up/shut-down function

We are now going to create another function to track the following:

  • Computer shutdowns (EventId 6006)

  • Computer startups (EventId - it's 6005)

The function should return a table with the same structure as our first function (Time, Id, Event, User).

We are changing the following for the function:

  • Different EventIds: Uses EventId (not InstanceId) - 6005 for Startup, 6006 for Shutdown

  • Filtered events: Added Where-Object to only get events with EventId 6005 or 6006

  • User is "System": Hard-coded as "System" since these are system events, not user events

  • Event names: "Startup" and "Shutdown" instead of "Logon" and "Logoff"

Combining the Functions into One Script

Part 5: Using dot notation to call our functions from the script we've made

What is dot notation?

Dot sourcing loads a script and keeps everything in the current session.

Dot notation in our script

  • Finds your Login_Logoff_AND_Startup_Shutdown.ps1 file

  • Loads all the functions from it (Get-LoginEvents and Get-StartupShutdownEvents)

  • Makes them available so you can use them in the rest of your script

Last updated