我没想到或不希望输出中出现转义序列。第一行输出是:
00000000000000001B 5B 33 32 3B 31 6D4C 6F 63 61 6C 41 64 64 72�[32;1m本地地址
PS C:\src\t> Get-NetTCPConnection | Where-Object { $_.State -eq 'Established' } | Out-File -FilePath '.\task3.txt' -Encoding ascii
PS C:\src\t> Get-Content .\task3.txt -first 2 | Format-Hex
Label: String (System.String) <5F8755A9>
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 1B 5B 33 32 3B 31 6D 4C 6F 63 61 6C 41 64 64 72 �[32;1mLocalAddr
0000000000000010 65 73 73 20 20 20 20 20 20 20 20 20 20 20 20 20 ess
0000000000000020 20 20 20 20 20 20 20 20 20 20 20 4C 6F 63 61 6C Local
0000000000000030 50 6F 72 74 20 52 65 6D 6F 74 65 41 64 64 72 65 Port RemoteAddre
0000000000000040 73 73 20 20 20 20 20 20 20 20 20 20 20 20 20 20 ss
0000000000000050 20 20 20 20 20 20 20 20 20 52 65 6D 6F 74 65 50 RemoteP
0000000000000060 6F 72 74 20 53 74 61 74 65 20 20 20 20 20 20 20 ort State
0000000000000070 41 70 70 6C 69 65 64 53 65 74 74 69 6E 67 20 4F AppliedSetting O
0000000000000080 77 6E 69 6E 67 50 72 6F 63 65 73 73 1B 5B 30 6D wningProcess**�[0m**
我注意到它没有出现在 Get-ChildItem 的输出中。
PS C:\src\t> dir *.g* | Out-File -FilePath '.\task5.txt' -Encoding ascii
PS C:\src\t> Get-Content -Path '.\task5.txt' -First 2 | Format-Hex
Label: String (System.String) <5A0214B6>
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 20 20 20 20 44 69 72 65 63 74 6F 72 79 3A 20 43 Directory: C
0000000000000010 3A 5C 73 72 63 5C 74 :\src\t
汤姆的有用回答 https://stackoverflow.com/a/71199341/45375提出了一个重要的观点:Out-*
cmdlet 旨在用于人的眼球, 不是为了程序化处理.
抛开这一点:
事实是ANSI / 虚拟终端转义序列 https://en.wikipedia.org/wiki/ANSI_escape_code- 用于生产colored在这种情况下的输出 - 出现在输出文件中意味着您正在使用PowerShell(核心)7.2+,其中的值$PSStyle.OutputRendering https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#psstyle确定这些转义序列是否是retained在输出中 - 隐式或显式 - 调用Out-*
cmdlet:
-
Use $PSStyle.OutputRendering = 'Host'
限制在格式化输出中使用转义序列以将输出发送到display(主机/控制台/终端),并进行所有其他用途 - 发送输出到一个文件>
(实际上是Out-File
) or 通过管道- 导致删除这些转义序列以产生纯文本 output.
- Add
$PSStyle.OutputRendering = 'Host'
给你的$PROFILE file https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Profiles使此行为成为未来会话的默认行为。
-
遗憾的是,从 PowerShell 7.2.1 开始,default的价值$PSStyle.OutputRendering
is 'Ansi'
, which 无条件地在格式化输出中包含转义序列。
-
'Host'
将产生更明智的默认值,与类 Unix 平台上的 CLI 所表现出的行为一致,当它们的 stdout 输出未连接到terminal- 除非明确要求包含它们,并带有诸如--color=always
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)