下面的代码抛出运行时异常 System.Collection.Hashtable 不包含名为“Trim”的方法下面脚本的最佳解决方案是什么?我只是想提取用户名。 IP 地址、计算机名称、打印的页面,并将其导出到 csv 文件。
$logPath = "Micros<sub>your text</sub>oft-Windows-PrintService/Operational"
$eventId = 307
$ipAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias (Get-NetConnectionProfile).InterfaceAlias).IPAddress
if (-not $ipAddress) {
$ipAddress = "NoIPAddress"
}
$todayDate = (Get-Date).ToString("yyyy-MM-dd")
$csvFilePath = "C:\test\$ipAddress-$todayDate.csv"
$filteredEvents = Get-WinEvent -LogName $logPath -FilterXPath "*[System[(EventID=$eventId) and (TimeCreated[timediff(@SystemTime) <= 86400000])]]"
if ($filteredEvents.Count -eq 0) {
Write-Host "No events found with Event ID $eventId in log $logPath for today or yesterday."
} else {
$eventsToExport = @() # Initialize the array
foreach ($event in $filteredEvents) {
$eventDate = $event.TimeCreated.Date
if ($eventDate -eq (Get-Date).Date -or $eventDate -eq (Get-Date).AddDays(-1).Date) {
$messageParts = $event.Message -split "`r`n"
$user = $printer = $pagesPrinted = $timeCreated = $hostName = $port = $null
foreach ($line in $messageParts) {
if ($line -match "owned by\s+(.+?)\s+on\s+(.+?)\s+was printed on\s+(.+?)\s+through port\s+(.+?)\.\s+Size in bytes: .+ Pages printed: (\d+)\.") {
$user = $Matches.Trim()
$hostName = $Matches.Trim()
$printer = $Matches.Trim()
$port = $Matches.Trim()
$pagesPrinted = $Matches.Trim()
Write-Host "Matched User: $user, HostName: $hostName, Printer: $printer, Port: $port, Pages Printed: $pagesPrinted"
} else {
Write-Host "No matches found for line: $line"
}
}
$eventsToExport += [PSCustomObject]@{
User = $user
Printer = $printer
PagesPrinted = $pagesPrinted
TimeCreated = $event.TimeCreated.ToString("M/d/yyyy H:mm")
HostName = $hostName
Port = $port
IP = $ipAddress
}
}
}
if ($eventsToExport.Count -gt 0) {
$eventsToExport | Export-Csv -Path $csvFilePath -NoTypeInformation -Encoding UTF8
Write-Host "Filtered events with Event ID $eventId for today or yesterday saved to $csvFilePath"
} else {
Write-Host "No events found for today or yesterday."
}
}
$Matches
自动变量是匹配值的哈希表。使用索引来访问元素。索引 0 包含整个匹配项,其他匹配项从左到右排列。用这样的东西更新你的代码:
$user = $Matches[1].Trim()
$hostName = $Matches[2].Trim()
$printer = $Matches[3].Trim()
$port = $Matches[4].Trim()
$pagesPrinted = $Matches[5].Trim()
有关 Powershell 中正则表达式的更多信息,请参阅 this。