首页 > 解决方案 > 使用 Powershell 打印包含制表符的 txt 文件

问题描述

标签: powershellcsvprintingxps

解决方案


You're close, and you stumbled onto a workaround yourself - the use of Out-String. You can add Out-String to the pipeline before sending the content to the printer:

Get-Content $fname | Out-String | Out-Printer -Name "Microsoft XPS Document Writer"

If the above isn't working for you you can try processing the tab character yourself:

( Get-Content $fname -Raw ).Split( "`t" ) -Join "`t"

If that displays the output as you're expecting, you can pipe that to Out-Printer (Out-String isn't necessary because -Join concatenates into a string):

( Get-Content $fname -Raw ).Split( "`t" ) -Join "`t" |
  Out-Printer -Name "Microsoft XPS Document Writer"

However, this seems like it may be a bug with Out-Printer, as comments and other answers have yielded varying success rates. The workarounds above are known to work on at least Windows 10.0.15063.0 (the version I'm currently running and tested with), but may have stopped working in later versions.

You may try converting the tabs to spaces as a workaround:

# This is set to 5 spaces here, but can be any number of
# spaces you want to represent a tab character
$replaceTabString = "     "
( Get-Content $fname -Raw ).Replace( "`t", $replaceTabString ) |
  Out-Printer -Name "Microsoft XPS Document Writer"

推荐阅读