Sorry to ask such a question, but I've spent 1/2 hour on this and no good solution.
I want to get the latest date from the Event Log for a particular app. So far, my code is:
$event = get-eventlog -logname 'Windows PowerShell' -source mpkLogParser -newest 1 | Format-List
echo $event
this yields:
Index : 51
EntryType : Information
InstanceId : 3001
Message : MPKLogParser successfully parsed the log file u_ex100118.log
Category : (1)
CategoryNumber : 1
ReplacementStrings : {MPKLogParser successfully parsed the log file u_ex100118.log}
Source : mpkLogParser
TimeGenerated : 1/28/2010 11:24:08 AM
TimeWritten : 1/28/2010 11:24:08 AM
UserName :
So how do I extract the TimeWritten part from $event?
Any help with this and I can sleep better. :)
Don't use Format-List unless you are displaying to the host. That is, don't use Format-List when assigning to a variable. Try this:
$name = 'Windows PowerShell'
$event = get-eventlog -logname $name -source mpkLogParser -newest 1
$event.TimeWritten
Related
How to get from applocker winevent only path of file and name of file (file.exe), i mean how to filter this info
Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL"
Have a look at the below, to see if this helps your use case. I too, don't have this on a system I can test at this point.
<#
Pull all AppLocker logs from the live AppLocker event log
(requires Applocker)
#>
Get-WinEvent -logname "Microsoft-Windows-AppLocker/EXE and DLL"
<#
Search for live AppLocker EXE/MSI block events: "(EXE) was prevented
from running":
#>
Get-WinEvent -FilterHashtable #{
logname = 'MicrosoftWindows-Applocker/EXE and DLL'
id = 8004
}
<#
Search for live AppLocker EXE/MSI audit events: "(EXE) was allowed
to run but would have been prevented from running if the AppLocker
the policy was enforced":
#>
Get-WinEvent -FilterHashtable #{
logname = 'MicrosoftWindows-Applocker/EXE and DLL'
id = 8003
}
Get-AppLockerEvent - Get event details related to AppLocker
activity
AppLocker events include a number of helpful details that are buried
within the event object or XML. This function will extract helpful
information like the username, rule name, file path, file hash, and
file signature details for easy viewing.
Download: Get-AppLockerEvent.ps1
That log is empty on my machine, but maybe you can do something with the xml from the event:
[xml]$xml = get-winevent application | select -first 1 |
foreach { $_.toxml() }
$xml.event
xmlns System EventData
----- ------ ---------
http://schemas.microsoft.com/win/2004/08/events/event System EventData
Oh I see, you have to restart the appidsvc after setting the group policy. You can use the filepath or fullfilepath properties:
$a = get-winevent "microsoft-windows-applocker/exe and dll" |
select -first 1
[xml]$xml = $a.toxml()
$xml.event.userdata.RuleAndFileData
xmlns : http://schemas.microsoft.com/schemas/event/Microsoft.Windows/1.0.0.0
PolicyNameLength : 3
PolicyName : EXE
RuleId : {fd686d83-a829-4351-8ff4-27c7de5755d2}
RuleNameLength : 24
RuleName : (Default Rule) All files
RuleSddlLength : 53
RuleSddl : D:(XA;;FX;;;S-1-5-32-544;(APPID://PATH Contains "*"))
TargetUser : S-1-5-21-1528843147-373324174-1919417754-1001
TargetProcessId : 3876
FilePathLength : 51
FilePath : %PROGRAMFILES%\GOOGLE\CHROME\APPLICATION\CHROME.EXE
FileHashLength : 0
FileHash :
FqbnLength : 1
Fqbn : -
TargetLogonId : 0x4d253a0
FullFilePathLength : 59
FullFilePath : C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
I am trying to find out the Name/Value mappings of the "State" data in the message of the 'Network Connected' event log:
Path = Microsoft-Windows-NetworkProfile/Operational
Source = NetworkProfile
Event ID = 10000
So I figured I'll write a custom event log by the same provider and to the same log (path) while changing the "State" value of the message, then I can see the name mapping of that value in the event viewer.
For example, I have these Value/Name mappings so far:
1 --> 'Connected'
5 --> 'Connected, IPV4 (Local)'
9 --> 'Connected, IPV4 (Internet)'
and I want to know the rest of them.
So I tried the New-WinEvent CmdLet in PowerShell to write the logs:
New-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -Id 10000 -Payload #("SSID","Description","{B58F86AB-F35D-4F73-A41E-98EA359E1D08}",0,1,0)
And it was created, but the last 4 arguments I passed to the -Payload parameter were not taking effect. Only the {"name" = "SSID" and "Description" = "Description"} were appearing in that event. The last 4 arguments stay at fixed values no matter how I change them, while there were no errors or warnings when executing this line, neither did -Verbose show anything.
I passed these arguments (especially last 3) in all types and values available. I even passed the arguments of an earlier event log (Not logged by me) to this parameter suspecting I was mistaking the data-types but nothing changed.
$a = ((Get-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -MaxEvents 50 | Where-Object {$_.Id -eq 10000})[-1]).properties[3].value
$b = ((Get-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -MaxEvents 50 | Where-Object {$_.Id -eq 10000})[-1]).properties[4].value
$c = ((Get-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -MaxEvents 50 | Where-Object {$_.Id -eq 10000})[-1]).properties[5].value
New-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -Id 10000 -Payload #("SSID","Description","{B58F86AB-F35D-4F73-A41E-98EA359E1D08}",$a,$b,$c)
Then I tried the Write-EventLog CmdLet:
Write-EventLog -LogName "Microsoft-Windows-NetworkProfile/Operational" -Source "NetworkProfile" -EventID 10000 -EntryType Information -Message $msg -Category 0
But I kept getting the error: Write-EventLog : The source name "NetworkProfile" does not exist on computer "localhost". Although the source does exist and it's the source of the 'Network Connected' log, as you can see from the screenshot.
What am I doing wrong with these 2 CmdLets?
I managed to make the first CmdLet New-WinEvent work. Oddly it was a data type issue.
The 'Network Connected' event expects 6 arguments for its message. The expected types for these arguments can be seen in this Warning I got from PowerShell
WARNING: Provided payload does not match with the template that was defined for event id 1000. The defined template is following:
I was passing the Guid argument as a string, but it expects it to have a [System.Guid] type, and apparently New-WinEvent doesn't give warnings when you pass the 6 arguments of the -Payload parameter in an array, even if one argument doesn't have the right type. It just creates a new event with some fixed default arguments (like what was happening in my problem).
So I had to cast the right type to this argument Guid. I got the name of its type from this:
$validEvent = (Get-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -MaxEvents 500 | Where-Object {$_.Id -eq 10000} | Where-Object {$_.properties[4].Value -eq 9})[-1]
$validEvent.Properties[2].Value.GetType().FullName
Then I casted the right types to the arguments and passed them to -Payload and it worked:
$name = 'SSID'
$desc = 'Description'
[System.Guid]$guid = "c48f86ab-f35d-4f73-a41e-99ea359e1d08"
[System.UInt32]$type = 1
[System.UInt32]$state = 63
[System.UInt32]$categ = 2
New-WinEvent -ProviderName Microsoft-Windows-NetworkProfile -Id 10000 -Payload #($name, $desc, $guid, $type, $state, $categ)
Then I could change the value of $state to get its name mapping from the $newLog.Message.
However, the second CmdLet Write-EventLog didn't work; apparently it can't write to this log by the same provider.
As Max mentioned, this CmdLet can only write to the "classic" event log, that's why it couldn't find the NetworkProfile source.
Some links that helped me along the way:
How to store an object in the Windows Event Log? [Answer] by Grady G Cooper
Writing to the event log in .NET - the right way
MSDN - Event Sources
TechNet - New-WinEvent
I have a large script which looks at certain event logs. Part of it is the following command:
Get-EventLog -ComputerName $computer -InstanceId 4625 -LogName Security -After $date -ErrorAction Stop | Select TimeWritten,#{n='Reason for Failure';e={$_.ReplacementStrings[8]}}
I receive the following output:
TimeWritten Reason for Failure
----------- ------------------
08/05/2018 10:55:06 %%2313
08/05/2018 09:19:24 %%2313
08/05/2018 07:49:22 %%2304
08/05/2018 07:49:22 %%2304
Is it possible to change the output in the reason for failure column to some other message. I know of the -replace operator but I am struggling on how to incorporate this?
This should get you headed in the right direction:
$failures = #{'%%2313' = 'Unknown User Name or Bad Password';
'%%2304' = 'An Error occured during Logon'
}
Get-EventLog -ComputerName $computer -InstanceId 4625 -LogName Security -After $date -ErrorAction Stop | Select TimeWritten,#{n='Reason for Failure';e={$failures[$_.Message]}}
Change $_.Message to be whichever field has the error code.
In Security section in Event Viewer, there is a column named "Computer".
I am using powershell to retrieve "all event ID 100" as of yesterday and display columns "event ID" and "computer".
Get-EventLog Security -After "2016-08-25 08:08:08" | Where-Object { ($_.instanceid) -eq 100 } | select-object "computer", "instanceID"
However, it only shows blank records for Computer column.
Please help. Thank you.
Try it with MachineName like so
... select-object "MachineName", "instanceID"
You can find that out when piping your objects to
Get-EventLog ... | Get-Member
where you will find a property MachineName
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