Query Details

Function: LastPowerShellExecutions ()

Last Power Shell Executions

Query

// Returns the last x amount of powershell executions based on a device and the timespan. Timespan examples can be seen in https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/scalar-data-types/timespan
let LastPowerShellExecutions = (DeviceNameInput: string, Results: int, TimeFrame: timespan) {
    DeviceProcessEvents
    | where TimeGenerated > ago(TimeFrame)
    | where DeviceName =~ DeviceNameInput
    // Function does by default filter system executions, if you want them included exclude the line below.
    | where not(AccountSid == "S-1-5-18")
    | where ProcessCommandLine contains "powershell"
    | top Results by TimeGenerated
    | project TimeGenerated, ActionType, ProcessCommandLine
};
// Example
LastPowerShellExecutions("devicename.tld", 100, 1d)

About this query

Explanation

The query defines a function called LastPowerShellExecutions that retrieves recent PowerShell command executions from a specified device. Here's a simple breakdown of how it works:

  1. Inputs: The function takes three inputs:

    • DeviceNameInput: The name of the device you want to check.
    • Results: The number of recent PowerShell executions you want to see.
    • TimeFrame: The time period you want to look back over to find these executions.
  2. Process:

    • It searches through a dataset called DeviceProcessEvents.
    • It filters the data to include only events from the specified device (DeviceNameInput) and within the specified time frame (TimeFrame).
    • It excludes system account executions by default (those with AccountSid equal to "S-1-5-18").
    • It looks for events where the command line contains "powershell", indicating a PowerShell execution.
  3. Output:

    • It returns the top Results number of PowerShell executions, sorted by the time they occurred.
    • The output includes the timestamp, action type, and the command line used for each execution.
  4. Example Usage:

    • To get the last 100 PowerShell executions from a device named "devicename.tld" within the past day, you would call the function like this: LastPowerShellExecutions("devicename.tld", 100, 1d).

This function is useful for monitoring and auditing PowerShell activity on specific devices over a defined period.

Details

Bert-Jan Pals profile picture

Bert-Jan Pals

Released: October 20, 2024

Tables

DeviceProcessEvents

Keywords

Device

Operators

letwhereago=~not==containstopbyproject

Actions

GitHub