Most commands that do print out those color codes explicitly check if stdout/stderr is a tty (using the isatty function).
If you want to preserve the color codes, you can run it within a terminal emulator like screen
or the direct logger script
, saving the output to a file.