本文介绍了Powershell 2.0 在字符之间生成空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 powershell 2.0:

With powershell 2.0:

write-output "abcd" >> mytext.txt  

返回:

a nul b nul c nul d nul

od -c 将 nul 显示为真正的二进制零, \0 ,或: a \0 b \0 c \0 d \0 (和 \0>\r \0 \n \0).

od -c shows the nul as a true binary zero, \0 , or: a \0 b \0 c \0 d \0 (and \r \0 \n \0).

我正在尝试生成一些 SQL,所以我认为这行不通.关于发生了什么以及如何使用写入输出来获取指定字符的任何想法?

I am trying to generate some SQL, so I don't think this will do. Any ideas of what's going on and how to use write-output to just get the specified characters?

推荐答案

这是因为 write-output 默认为 UTF-16 文本编码,即每个字符 2 个字节.当您处理符合 ASCII 代码页范围的文本时,每个字符的第二个字节将为零.

This is because write-output defaults to UTF-16 text encoding, which is 2 bytes per character. When you are dealing with text that fits into the ASCII codepage range, the 2nd byte of each character will be zero.

这由 $OutputEncoding 全局变量控制,因此您可以将其设置为 ASCII.

This is controlled by the $OutputEncoding global variable, so you could set that to ASCII.

另一种选择是使用 cmdlet Out-File,它具有显式编码参数.我建议您使用它而不是输出重定向,因为这样可以避免您全局更改环境(通过设置全局首选项变量 $OutputEncoding)

Another option is to use the cmdlet Out-File, which has an explicit encoding parameter. I would suggest you use this instead of output redirection, because that saves you from changing your environment globally (by setting the global preference variable $OutputEncoding)

使用 Out-File,并将编码设置为 ASCII,您的示例将如下所示:

Using Out-File, and setting encoding to be ASCII, your example would look like this:

"abcd" | out-file "mytext.txt" -Encoding ASCII

请注意,并非所有字符都可以用 ASCII 表示,您应该确定这是否适合您的用途.就我个人而言,我通常会选择 UTF-8,因为当字符落在 0-127 的 ASCII 范围内时,它与 ASCII 等效,但也处理国际字符.关于文本编码的强制性链接.

Do be aware that not all characters are representable in ASCII, and you should determine whether this is an appropiate encoding for your purpose. Personally I would typically go for UTF-8, since it is ASCII equivalent when characters fall in the ASCII range from 0-127, but also handles international characters. Obligatory link about text encoding.

这篇关于Powershell 2.0 在字符之间生成空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:56