如何修复Get-ChildItem -Recurse以处理第一级以上的问题

时间:2019-04-18 11:26:27

标签: powershell export-to-csv powershell-v3.0 event-log

我尝试使用Get-ChildItem从给定文件结构中从事件日志中过滤Windows事件(id = 4633)。

文件结构如下:

C:\ Temp \ raw_data \ 2018-09 \ Securitylog \ Securitylog_2018-09-14_13-30.evtx

问题是Get-ChildItem仅处理第一级。低于第一个级别的每个级别似乎都被忽略了。

我尝试使用-Recurse参数没有成功。我没有收到任何错误,因此我相信语法是正确的。代码样本如下。

$out = New-Object System.Text.StringBuilder
$out.AppendLine("ServerName,EventID,TimeCreated,UserName,File_or_Folder,AccessMask")
$ns = @{e = "http://schemas.microsoft.com/win/2004/08/events/event"}
Get-ChildItem "C:\temp\raw_data" -Recurse | ForEach-Object {
    {
        $evts = Get-WinEvent -FilterHashtable @{Path=$_;id="4663"} -Oldest
        foreach ($evt in $evts) {
            $xml = $evt.ToXml()
            $SubjectUserName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='SubjectUserName']/text()" |
                               Select-Object -ExpandProperty Node |
                               Select-Object -ExpandProperty Value
            $ObjectName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='ObjectName']/text()" |
                          Select-Object -ExpandProperty Node |
                          Select-Object -ExpandProperty Value
            $AccessMask = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='AccessMask']/text()" |
                          Select-Object -ExpandProperty Node |
                          Select-Object -ExpandProperty Value
            $out.AppendLine("$($svr),$($evt.id),$($evt.TimeCreated),$SubjectUserName,$ObjectName,$AccessMask")
            Write-Host $svr
            Write-Host $evt.id, $evt.TimeCreated, $SubjectUserName, $ObjectName,$AccessMask
        }
    }
}
$out.ToString() | Out-File -FilePath "C:\Temp\X4663Events.csv"

我不知道为什么不处理任何文件。文件将被创建,但标题为空。

1 个答案:

答案 0 :(得分:0)

不必那么难。典型的powershell看起来更像这样。构建一个对象,然后导出到csv。知道自己在做什么,并验证每一件。

$evts = get-winevent security -MaxEvents 3

$objs = foreach ($evt in $evts) {
  [xml]$xml = $evt.toxml()

  $subjectusername = $xml.event.EventData.data |
    where name -eq subjectusername |
    select -expand '#text'
  $subjectdomainname = $xml.event.EventData.data |
    where name -eq subjectdomainname |
    select -expand '#text'

  [pscustomobject]@{
    SubjectUserName = $subjectusername
    SubjectDomainName = $subjectdomainname
  }

}

$objs
$objs | export-csv mylog.csv
get-content mylog.csv


SubjectUserName SubjectDomainName
--------------- -----------------
SYSTEM          NT AUTHORITY
MYCOMP$         AD
MYCOMP$         AD


#TYPE System.Management.Automation.PSCustomObject
"SubjectUserName","SubjectDomainName"
"SYSTEM","NT AUTHORITY"
"MYCOMP$","AD"
"MYCOMP$","AD"