bat 脚本打印输出彩色文字

要在 Windows 批处理脚本中打印彩色内容,通常的方式是 echo [32mHello World[0m,但这种方式需要输入特殊字符 ESC(ASCII 码为 27),我试过 Alt+027 的快捷键却怎么也打不出来这个字符,而且这种方式各个颜色的编码也很不好记,分享一种更简单的方法!

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
powershell -Command "Write-Host 'This is Black' -ForegroundColor White -BackgroundColor Black"
powershell -Command "Write-Host 'This is DarkBlue' -ForegroundColor White -BackgroundColor DarkBlue"
powershell -Command "Write-Host 'This is DarkGreen' -ForegroundColor White -BackgroundColor DarkGreen"
powershell -Command "Write-Host 'This is DarkCyan' -ForegroundColor White -BackgroundColor DarkCyan"
powershell -Command "Write-Host 'This is DarkRed' -ForegroundColor White -BackgroundColor DarkRed"
powershell -Command "Write-Host 'This is DarkMagenta' -ForegroundColor White -BackgroundColor DarkMagenta"
powershell -Command "Write-Host 'This is DarkYellow' -ForegroundColor White -BackgroundColor DarkYellow"
powershell -Command "Write-Host 'This is Gray' -ForegroundColor Black -BackgroundColor Gray"
powershell -Command "Write-Host 'This is DarkGray' -ForegroundColor White -BackgroundColor DarkGray"
powershell -Command "Write-Host 'This is Blue' -ForegroundColor White -BackgroundColor Blue"
powershell -Command "Write-Host 'This is Green' -ForegroundColor White -BackgroundColor Green"
powershell -Command "Write-Host 'This is Cyan' -ForegroundColor Black -BackgroundColor Cyan"
powershell -Command "Write-Host 'This is Red' -ForegroundColor White -BackgroundColor Red"
powershell -Command "Write-Host 'This is Magenta' -ForegroundColor White -BackgroundColor Magenta"
powershell -Command "Write-Host 'This is Yellow' -ForegroundColor Black -BackgroundColor Yellow"
powershell -Command "Write-Host 'This is White' -ForegroundColor Black -BackgroundColor White"

其中单引号内是打印的文字内容,ForegroundColor 参数传文字颜色,BackgroundColor 参数传背景颜色,直接传颜色名字,非常方便。

如果在批处理中使用,可以定义一个函数,调用起来更简洁。

1
2
3
4
5
6
7
8
9
@echo off

call :print "Hello, world!" Yellow Red
call :print "Hello, iMaeGoo!" White Blue
exit /b 0

:print
powershell -Command "Write-Host '%1' -ForegroundColor %2 -BackgroundColor %3"
goto:eof

效果

bat 脚本打印输出彩色文字

https://www.imaegoo.com/2025/bat-color/

作者

iMaeGoo

发布于

2025-08-06

更新于

2025-08-06

许可协议

CC BY 4.0

评论