How to print process ıd in event log? - powershell

Im trying to get process id from my Get-Eventlog. I can not parse the process id from the message. How ı can get it from there ? I tried With Select string -Pattern but it did not worked. My powershell code :
$directory = E:\BpLnfgDsc2.txt
$message = Get-EventLog -log Security -InstanceId 4663 -Newest 1 | Where {$_.message -match "Object Name:\s*$directory"} | foreach {$_.Message}
And here is my output:
PS C:\WINDOWS\system32> $message
An attempt was made to access an object.
Subject:
Security ID: Some-id
Account Name: tester
Account Domain: DESKTOP
Logon ID: Some-Id
Object:
Object Server: Security
Object Type: File
Object Name: E:\BpLnfgDsc2.txt
Handle ID: Some-Id
Resource Attributes: S:AI
Process Information:
Process ID: 0xd34
Process Name: C:\Windows\explorer.exe
Access Request Information:
Accesses: %%4423
Access Mask: 0x80
My expected output:
0xd34

You can extend your regex matching pattern a bit more to also capture the process ID and output it with the automatically populated variable $matches.
I've chosen a capture group name for clarity, you could also just use number captured groups. I also added (?s) at the beginning of the pattern to treat the multiline message string as a single line
$message = Get-EventLog -log Security -InstanceId 4663 -Newest 1 |
Where-Object {$_.message -match "(?s)Object Name:\s*$directory.+Process ID:\s+(?<ProcessID>\S+)"} |
ForEach-Object {$matches.ProcessID}

Related

Get-WinEvent and Select-string filter line result

I´m trying to use get-winevent + select string to filter and get the IP from events 4625.
After get-winevent I want to filter the results to show only "Source Network Address:" line, which will provide me the list of IP´s I need to block.
Below is an example of the results, thanks in advance!
PS C:\Users\Administrator> Get-WinEvent -FilterHashtable #{LogName='Security';ID=4625} -MaxEvents 1 | fl
TimeCreated : 15/02/2023 07:43:25
ProviderName : Microsoft-Windows-Security-Auditing
Id : 4625
Message : An account failed to log on.
Subject:
Security ID: S-1-0-0
Account Name: -
Account Domain: -
Logon ID: 0x0
Logon Type: 3
Account For Which Logon Failed:
Security ID: S-1-0-0
Account Name: ADMINISTRATOR
Account Domain:
Failure Information:
Failure Reason: Unknown user name or bad password.
Status: 0xC000006D
Sub Status: 0xC0000064
Process Information:
Caller Process ID: 0x0
Caller Process Name: -
Network Information:
Workstation Name: -
Source Network Address: 209.45.48.94
Source Port: 0
Detailed Authentication Information:
Logon Process: NtLmSsp
Authentication Package: NTLM
Transited Services: -
Package Name (NTLM only): -
Key Length: 0
Get-WinEvent -FilterHashtable #{LogName='Security';ID=4625} -MaxEvents 100 | Select-String -Pattern "Source Network Address:" tried this way but no results showed
(Get-WinEvent -FilterHashtable #{LogName='Security';ID=4625} -MaxEvents 1).Message.split(':') -split("`t") | ? { $_ -match '\d+\.\d+\.\d+.\d+'} | % {$_ -replace ("`n","")}
As it seems you need to extract an IP-address, I would suggest to use a regex for matching it.
$regex = [regex]::new("\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")
Get-WinEvent -FilterHashtable #{LogName='Security';ID=4625} -MaxEvents 100 | Foreach {$regex.Match($_.Message).Value}
This code loops through each result which Get-WinEvent returns and checks with the regex for an IP-address in the message property. When no match is found it will return an empty line.
To get information from the Windows Event log, it is cumbersome to try and parse that out of the Message string.
Better look at the XML where the values can be found under their own attribute names:
$result = Get-WinEvent -FilterHashtable #{LogName='Security';ID=4625} -MaxEvents 100 | ForEach-Object {
# convert the event to XML and grab the Event node
$eventXml = ([xml]$_.ToXml()).Event
# output the values from the XML representation
[PsCustomObject]#{
UserName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
IpAddress = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'IpAddress' }).'#text'
EventDate = [DateTime]$eventXml.System.TimeCreated.SystemTime
}
}
Now, if all you want from this is the list of IP addresses, just do
$result.IpAddress
Thank you all, for quick reply!

Extract Username From Log Text using Powershell

I'm trying to extract all usernames that has failed login atempts from Event Viewer log and then list only the usernames. However the data for each entry is text so I have a hard time extracting only the names (Intruder123 in this case). It would be a couple of hundred account names stored in an array.
$String = Get-WinEvent #{LogName='Security';ProviderName='Microsoft-Windows-Security-Auditing';ID=4625 } -ComputerName SECRETSERVER |
Select-Object -ExpandProperty Message
$string -match "Account Name: (?<content>.*)"
$matches['content']
The data looks like this (multiple times):
Account For Which Logon Failed:
Security ID: S-1-0-0
Account Name: Intruder123
Account Domain: SECRET.LOCAL
I think you could collect some more information like the time the failed logon happened and on which computer. For that, create a resulting array of objects.
Also, trying to parse the Message property can be cumbersome and I think it is much better to get the info from the Event as XML:
$filter = #{LogName='Security';ProviderName='Microsoft-Windows-Security-Auditing';ID=4625 }
$result = Get-WinEvent -FilterHashtable $filter -ComputerName SECRETSERVER | ForEach-Object {
# convert the event to XML and grab the Event node
$eventXml = ([xml]$_.ToXml()).Event
$userName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
$computer = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'WorkstationName' }).'#text'
# output the properties you need
[PSCustomObject]#{
Time = [DateTime]$eventXml.System.TimeCreated.SystemTime
UserName = $userName
Computer = $computer
}
}
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'X:\FailedLogons.csv' -NoTypeInformation

powershell script - timegenerated in security log

i need some help with this code, as i'm a super-beginner with powershell but trying to get a report to my manager who is looking to see failed external attempts to remote into our system.
trying to pull out 4625 events from the security log and get the following fields into a csv file: Username (if it's an internal user), date of event, origin IP. I have this code so far based on what i could find (a.k.a. leech) online and customized a bit. everything is correct at this point except for the date (timegenerated). and i believe it's because of the replacementstring number listed. it's pulling the SubjectUserSid from the log. i'm not quite sure i understand how to find that replacementstring number, so maybe if someone can explain that to me, that would help.
thanks
$Date = [DateTime]::Now.AddDays(-1)
$Server = "SERVER"
$logName = '{0}{1}_security4625_log.csv' -f "C:\temp\",
$Date.tostring("MM-dd-yyyy_HH,mm,ss")
Get-EventLog -LogName 'Security' -Computer $Server `
-InstanceId 4625 `
-After $Date |
Select-Object #{
Name='TargetUserName'
Expression={$_.ReplacementStrings[5]}
},
#{
Name='WorkstationName'
Expression={$_.ReplacementStrings[1] -replace '\$$'}
},
#{
Name='IpAddress'
Expression={$_.ReplacementStrings[-2]}
},
#{
Name='TimeGenerated'
Expression={$_.ReplacementStrings[0]}
} |
Export-Csv -Path $logName -NoTypeInformation
Change the #{Name='TimeGenerated';Expression={$_.ReplacementStrings[0]} to simply TimeGenerated and you should be all set.
The ReplacementStrings are the variables from the Message field. Such as, the following log entry:
EventID : 4656
MachineName : AmazingLaptop.ChinchillaFarm.com
Data : {}
Index : 23277285
Category : (12804)
CategoryNumber : 12804
EntryType : FailureAudit
Message : A handle to an object was requested.
Subject:
Security ID: S-1-5-21-2127521184-6397854128-1234567890-12345678
Account Name: TMTech
Account Domain: ChinchillaFarm
Logon ID: 0xb8f705b
Object:
Object Server: SC Manager
Object Type: SERVICE OBJECT
Object Name: Schedule
Handle ID: 0x0
Resource Attributes: -
Process Information:
Process ID: 0x2b4
Process Name: C:\Windows\System32\services.exe
Access Request Information:
Transaction ID: {00000000-0000-0000-0000-000000000000}
Accesses: %%7186
%%7188
Access Reasons: -
Access Mask: 0x14
Privileges Used for Access Check: -
Restricted SID Count: 0
Source : Microsoft-Windows-Security-Auditing
ReplacementStrings : {S-1-5-21-2127521184-6397854128-1234567890-12345678, TMTech, ChinchillaFarm, 0xb8f705b...}
InstanceId : 4656
TimeGenerated : 11/20/2015 11:06:39 AM
TimeWritten : 11/20/2015 11:06:39 AM
UserName :
Site :
Container :
The ReplacementStrings are the values for all the fields like 'Security ID', 'Account Name', and 'Account Domain' within the Message property. Instead using one of those for the date/time you can just use the TimeGenerated property and it'll work just as well for your CSV.
Updated script:
$Date = [DateTime]::Now.AddDays(-1)
$Server = "SERVER"
$logName = '{0}{1}_security4625_log.csv' -f "C:\temp\",
$Date.tostring("MM-dd-yyyy_HH,mm,ss")
Get-EventLog -LogName 'Security' -Computer $Server `
-InstanceId 4625 `
-After $Date |
Select-Object #{
Name='TargetUserName'
Expression={$_.ReplacementStrings[5]}
},
#{
Name='WorkstationName'
Expression={$_.ReplacementStrings[1] -replace '\$$'}
},
#{
Name='IpAddress'
Expression={$_.ReplacementStrings[-2]}
},
TimeGenerated |
Export-Csv -Path $logName -NoTypeInformation

Match the User Name against the Security EventLog

I want to take a domain user and for it want to check the Security Event Logs for say Logon and then Print the events which match but it returns me null value:
Get-EventLog -Log Security -Computer PC1 -InstanceID 4624 -After(Get-Date).AddDays(-2) | ? {
$_.Message -match "Account Name:\s+qasimali\s" -and
$_.Message -match 'Logon Type:\s+(2|10)\s"
}
but it generates no data for output
Read-Host : name cannot be Null or Empty.
Whereas command runs and gives no error. I just want to check whether this command is running fine or not.
The way I have done this in the past is as follows ( Thoroughly Commented for clarity) :
## Set Username Input
$UserInput = "DOMAINUSER"
## Set date in past to retrieve events up to
$StartTime = ((Get-Date).AddMinutes(-2))
##Set Domain Controller to search on
$ComputerName = "DC1"
## Retrieve Event 4624 from DC Eveng Logs
$Logons = Get-WinEvent -ComputerName $ComputerName -FilterHashTable #{LogName="Security"; ID="4624"; StartTime=$StartTime;EndTime=(Get-Date)}
## Initialize variable to store outputs in
$EventOutput = #()
## Enumerate Events to retrieve usernames to compare against User Input
foreach ($Logon in $Logons) {
## Convert Event to XML
$LogonXML = [XML]$Logon.ToXML()
## Retrieve Username from XML Object
$LogonUser = (($LogonXML.Event.EventData.Data | Select "#text")[5])."#text"
## Retrieve Logon Type from XML Object
$LogonType = (($LogonXML.Event.EventData.Data | Select "#text")[8])."#text"
## Check Event Username matches User Input
if ($LogonUser -match $UserInput) {
## Check LogonType is correct
if ($LogonType -eq 2 -or $LogonType -eq 10) {
## Append Event Object to Event Output
$EventOutput += $Logon
}
}
}
## Output Resulting Event Output Object
$EventOutput
The Resulting Output can be manipulated to retrieve whatever details you wish. I find converting each Object to XML to parse further values useful.
NOTE : I've just thrown this together quickly from memory, this can be quickly restructured to enable other queries if required. Start and End Times will need to be changed to extract information from the correct timespan.

Powershell: How can I extract time from the message field of eventlog?

I'm trying to get unexpected shutdown times of Windows Sever 2008 machines via Get-EventLog in Powershell. I can get close by searching for events with an EventID of 6008 and selecting only message, but I need to parse within the field to grab the time it occurred (not the time the event fired).
I've tried to use replacementstrings[x] but I can't find how to specify the field to use (messages) and can't get a result.
get-eventlog -LogName System -ComputerName svr-name | Where-Object {$_.EventID -eq 6008 -AND $_.timegenerated -gt (get-date).adddays(-30)}| select message
Produces this:
Message
-------
The previous system shutdown at 3:35:32 AM on ‎7/‎29/‎2014 was unexpected.
The previous system shutdown at 3:40:06 PM on ‎7/‎10/‎2014 was unexpected.`
Retrieving all events from a remote host and filtering them on the local machine ususally doesn't perform too well, because that way you transmit tons of unrelated events over the network, just to throw them away. Get-EventLog has options for filtering messages by Event ID or before/after a given timestamp on the source, so better use those for pre-selecting the messages you're actually interested in. The timestamp of the crash can be extracted from the Message field with a regular expression and parsed into a DateTime value via ParseExact():
$log = 'System'
$server = 'svr-name'
$id = [uint64]"0x80000000" + 6008
$date = (Get-Date).AddDays(-30)
$fmt = 'h:mm:ss tt on M\/d\/yyyy'
$culture = [Globalization.CultureInfo]::InvariantCulture
Get-EventLog -LogName $log -ComputerName $server -InstanceId $id -After $date | ? {
$_.Message -match 'at (\d+:\d+:\d+ [ap]m on \d+/\d+/\d+) was unexpected'
} | select MachineName, TimeGenerated,
#{n='Crashtime';e={[DateTime]::ParseExact($matches[1], $fmt, $culture)}}
The pipeline produces a list of objects with the properties MachineName, TimeGenerated and Crashtime (the last one being a calculated property). If you collect the output of the pipeline in a variable (e.g. $evt) you can access the Crashtime property of the third object like this:
$evt = .\script.ps1
$evt[2].Crashtime
Using regex, you can pull it out as such.
$Messages = (get-eventlog -LogName System -ComputerName svr-name | Where-Object {$_.EventID -eq 6008 -AND $_.timegenerated -gt (get-date).adddays(-30) }| select message)
$Messages | ForEach-Object {
$Matched = $_.Message -match "([0-9]{1,2}:.*[0-9]{4})"
if ($Matched) {
Write-Output "System rebooted at $($Matches[1])"
}
}
There might be a better way, but I do not know what :)
Example Output from my System
System rebooted at 4:34:30 PM on ‎4/‎20/‎2014
System rebooted at 1:48:38 PM on ‎1/‎21/‎2014
System rebooted at 1:37:12 PM on ‎1/‎21/‎2014
System rebooted at 1:22:01 PM on ‎1/‎21/‎2014
System rebooted at 4:41:21 PM on ‎11/‎22/‎2013
More easy
get-eventlog system | where-object {$_.EventID -eq "6008"} | fl