The following code in powershell creates a file with key/value pairs.
$result = @()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result = [PSCustomObject]@{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
#$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
$result | Out-File "C:\Temp\Logins.csv"
The above results in the following file contents:
However, I want the contents in CSV format. If I change the commented lines out as below:
$result = @()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result = [PSCustomObject]@{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
#$result | Out-File "C:\Temp\Logins.csv"
Googling around through myriad pages and examples, I (mis?)understand this to be a hashtable and that the Export-Csv should work to create a csv file. I cannot seem to get it to work.
Any help is greatly appreciated.
CodePudding user response:
Hmmm ... the following code works exactly like I'd expect it:
$result =
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM") {
[PSCustomObject]@{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
BTW: It is recommended not to use Get-Eventlog
anymore. Use Get-WinEvent
instead. ;-)
CodePudding user response:
Another option could be just this:
Clear-Host
$result = @()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-1)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result = [PSCustomObject]@{
Time = $PSItem.TimeGenerated
Workstation = $PSItem.ReplacementStrings[11]
}
}
}
$result | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath 'Logins.csv'
Get-Content -Path 'Logins.csv'
# Results
<#
"Time","Workstation"
...
"06-Aug-22 16:45:37","-"
"06-Aug-22 16:45:17","-"
"06-Aug-22 16:44:29","-"
...
#>