如何在不修改PowerShell Cmdlet输出的情况下为日志添加自定义日期
解决PowerShell中保留Get-Printer输出格式并添加自定义日期到日志的问题
你当前的问题出在直接将Get-Printer返回的对象与字符串拼接写入日志——PowerShell会自动将对象转换为默认的字符串表示(仅显示打印机名称),完全丢失了Get-Printer原本的表格格式,导致日志混乱。
以下是两种符合需求的实现方式,既能保留Get-Printer的原始输出格式,又能在对应设备的打印机信息上方或下方添加自定义日期:
方案1:日期放在设备打印机信息的上方
每次处理设备时重新生成日期(避免所有设备共用脚本启动时的时间),先写入日期+设备标识的分隔信息,再追加Get-Printer的原始输出:
$equipos = "D:\SCRIPTSM\despFi\cont-pla.txt" $listaEquipos = Get-Content $equipos foreach ($equipo in $listaEquipos){ Try { if (Test-Connection -ComputerName $equipo -Count 1 -Quiet){ # 实时获取当前操作的日期 $fecha = (Get-Date).ToString('dd.MM.yyyy "y en esta hora" HH:mm:ss') # 写入日志头部标识 "=== 设备 [$equipo] 的打印机信息 - 生成时间:$fecha ===" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append # 追加Get-Printer的原始格式输出 Get-Printer -ComputerName $equipo -ErrorAction Stop | Where-Object {$_.Name -notmatch "Fax|Microsoft|OneNote|PDF"} | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append # 写入空行分隔不同设备的信息,提升可读性 "" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append }else{ $fecha = (Get-Date).ToString('dd.MM.yyyy "y en esta hora" HH:mm:ss') "El equipo $equipo está apagado el día $fecha " | Out-File -FilePath D:\SCRIPTSM\ALV\fallos.log -Append } }catch{ $fecha = (Get-Date).ToString('dd.MM.yyyy "y en esta hora" HH:mm:ss') "$equipo se necesita reiniciar para sacar las impresoras instaladas $fecha" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append # 可选:将错误详情写入日志 "Error详情: $($Error[0].Exception.Message)" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append "" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append } }
方案2:日期放在设备打印机信息的下方
只需调整写入顺序,先输出打印机信息,再追加日期标识:
# 替换方案1中对应的代码块 if (Test-Connection -ComputerName $equipo -Count 1 -Quiet){ $fecha = (Get-Date).ToString('dd.MM.yyyy "y en esta hora" HH:mm:ss') # 先输出打印机原始格式 Get-Printer -ComputerName $equipo -ErrorAction Stop | Where-Object {$_.Name -notmatch "Fax|Microsoft|OneNote|PDF"} | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append # 再写入日期标识 "=== 设备 [$equipo] 的打印机信息获取完成 - 时间:$fecha ===" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append "" | Out-File -FilePath D:\SCRIPTSM\ALV\PRUEBA.log -Append }
关键注意点
- 不要直接将
Get-Printer返回的对象与字符串拼接,这会强制对象丢失格式转换为简单字符串。 - 使用
Out-File -Append代替>>:>>本质是调用Out-File,但直接管道到Out-File能更好地保留PowerShell对象的原生格式化输出。 - 每次处理设备时重新生成
$fecha,确保时间记录的是当前操作的实际时间,而非脚本启动时间。
内容的提问来源于stack exchange,提问作者AALV8
相关产品推荐
相关产品推荐

