简体   繁体   中英

powershell hashtable (export-Csv) to CSV

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"

Then I get the following: 在此处输入图像描述

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.

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. ;-)

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","-"
...
 #>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM