PowerShell脚本报错:System.Collection.Hashtable无Trim方法的解决方案
PowerShell打印日志提取异常修复方案
错误原因
抛出System.Collection.Hashtable does not contain a method named 'Trim'异常的核心问题:
$Matches是PowerShell正则匹配返回的哈希表对象,存储了正则分组的键值对,直接对整个哈希表调用字符串方法Trim()必然报错- 原代码未通过索引访问
$Matches内的具体匹配分组,错误地对整个哈希表执行操作
核心修改点
- 正则匹配结果正确取值:通过
$Matches[索引]获取对应分组的字符串值后,再调用Trim()去除首尾空格 - 修正日志路径错误:原代码中
Micros<sub>your text</sub>oft为输入错误,改为正确的打印服务日志路径Microsoft-Windows-PrintService/Operational - 优化日期判断逻辑:提前计算今日、昨日日期,避免循环内重复调用
Get-Date提升效率 - 简化匹配逻辑:直接对完整事件消息执行正则匹配,无需拆分逐行遍历
修复后的完整代码
$logPath = "Microsoft-Windows-PrintService/Operational" $eventId = 307 # 获取本地IPv4地址 $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" # 过滤最近24小时内的EventID 307事件 $filteredEvents = Get-WinEvent -LogName $logPath -FilterXPath "*[System[(EventID=$eventId) and (TimeCreated[timediff(@SystemTime) <= 86400000])]]" -ErrorAction SilentlyContinue if (-not $filteredEvents) { Write-Host "未找到今日或昨日Event ID为$eventId的打印日志事件。" } else { $eventsToExport = @() $today = (Get-Date).Date $yesterday = $today.AddDays(-1) foreach ($event in $filteredEvents) { $eventDate = $event.TimeCreated.Date if ($eventDate -eq $today -or $eventDate -eq $yesterday) { $user = $printer = $pagesPrinted = $hostName = $port = $null # 直接匹配整个事件消息 if ($event.Message -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[1].Trim() $hostName = $Matches[2].Trim() $printer = $Matches[3].Trim() $port = $Matches[4].Trim() $pagesPrinted = $Matches[5].Trim() Write-Host "匹配到记录:用户=$user,主机名=$hostName,打印机=$printer,端口=$port,打印页数=$pagesPrinted" } $eventsToExport += [PSCustomObject]@{ User = $user Printer = $printer PagesPrinted = $pagesPrinted TimeCreated = $event.TimeCreated.ToString("M/d/yyyy H:mm") HostName = $hostName Port = $port LocalIP = $ipAddress } } } if ($eventsToExport.Count -gt 0) { # 确保输出目录存在 $csvDir = Split-Path $csvFilePath -Parent if (-not (Test-Path $csvDir)) { New-Item -ItemType Directory -Path $csvDir | Out-Null } $eventsToExport | Export-Csv -Path $csvFilePath -NoTypeInformation -Encoding UTF8 Write-Host "日志提取完成,文件已保存至:$csvFilePath" } else { Write-Host "未筛选出今日或昨日的有效打印记录。" } }
额外优化说明
- 添加
-ErrorAction SilentlyContinue避免日志不存在时的报错 - 自动创建CSV输出目录,避免路径不存在导致导出失败
- 重命名
IP字段为LocalIP,语义更清晰
内容的提问来源于stack exchange,提问作者Bilguun Ayush
相关产品推荐
相关产品推荐

