如何在powershell.exe中取消Write-Warning等命令的自动换行?
PowerShell控制台中日文长串消息自动换行的解决办法
现象说明
- 在
powershell.exe控制台里,用Write-Warning或者Write-Debug输出无空格的日文字符串时,会被自动换行;但在PowerShell ISE里不会出现这个问题。 Write-Error不管是控制台还是ISE都会换行。Write-Host、Write-Output、Write-Information在两种环境下都能正常输出不换行。
示例代码
$message = "The quick brown fox jumps over the lazy dog. いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす." Write-Host ("Write-Host Message: {0}" -F $message) Write-Output ("Write-Output Message: {0}" -F $message) Write-Error ("Write-Error Message: {0}" -F $message) -ErrorAction Continue Write-Information ("Write-Information Message: {0}" -F $message) -InformationAction Continue Write-Warning ("Write-Warning Message: {0}" -F $message) -WarningAction Continue $DebugPreference = 'Continue' Write-Debug ("Write-Debug Message: {0}" -F $message)
在powershell.exe和PowerShell ISE中执行上述代码,会呈现不同的换行效果。
解决方法
要让Write-Error、Write-Warning、Write-Debug在控制台输出日文时不自动换行,可以用以下两种方式:
1. 自定义输出函数替代原生cmdlet
原生cmdlet的换行是因为内置的格式化逻辑在处理无空格CJK长串时强制拆分,绕过这个逻辑就能解决问题。可以写几个自定义函数:
# 自定义警告输出 function Write-CustomWarning { param([string]$Message) $originalColor = $Host.UI.RawUI.ForegroundColor $Host.UI.RawUI.ForegroundColor = 'Yellow' $Host.UI.WriteWarningLine($Message) $Host.UI.RawUI.ForegroundColor = $originalColor } # 自定义错误输出 function Write-CustomError { param([string]$Message) $originalColor = $Host.UI.RawUI.ForegroundColor $Host.UI.RawUI.ForegroundColor = 'Red' $Host.UI.WriteErrorLine($Message) $Host.UI.RawUI.ForegroundColor = $originalColor } # 自定义调试输出 function Write-CustomDebug { param([string]$Message) $originalColor = $Host.UI.RawUI.ForegroundColor $Host.UI.RawUI.ForegroundColor = 'Gray' $Host.UI.WriteDebugLine($Message) $Host.UI.RawUI.ForegroundColor = $originalColor }
之后直接调用这些自定义函数,替换原来的Write-Warning等,就能避免无空格日文字符串被强制换行。
2. 临时调整控制台缓冲区宽度
如果只是临时需求,可以增大控制台的缓冲区宽度,给长字符串足够的显示空间:
# 把缓冲区宽度设为1000,可根据实际字符串长度调整 $Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size(1000, $Host.UI.RawUI.BufferSize.Height)
这个方法的局限性是:如果字符串长度超过设置的缓冲区宽度,还是会换行,而且只对当前PowerShell会话有效。
原理补充
Write-Warning、Write-Error、Write-Debug这些cmdlet在控制台输出时,会经过PowerShell的格式化系统处理,这个系统会对无空格的CJK长串自动插入换行符。而Write-Host这类cmdlet是直接把内容输出到控制台,不经过额外格式化,所以不会换行。自定义函数通过调用Host.UI的底层输出方法,绕过了格式化系统的自动换行逻辑,从而实现无换行输出。
内容的提问来源于stack exchange,提问作者SATO Yusuke
相关产品推荐
相关产品推荐

