Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
powershell字符串操作是否会添加垃圾字符?_Powershell_Powershell 2.0 - Fatal编程技术网

powershell字符串操作是否会添加垃圾字符?

powershell字符串操作是否会添加垃圾字符?,powershell,powershell-2.0,Powershell,Powershell 2.0,当我将$string变量内容放入某个文本文件时,它似乎添加了一些垃圾字符。例如,我正在用字符串编写一个实用程序名称,并将该字符串复制到文件中,如下所示 $CodeCount+="ccount.exe" $CodeCount | Out-file "C:\CodeCount.bat" 当我执行这个批处理文件时,它失败了,因为它前面显示了一些垃圾字符 即使我尝试使用trim(),但结果仍然相同 如何避免在前面添加垃圾字符?这是因为输出文件所使用的标准编码是Unicode,它在文件的开头添加了一些

当我将$string变量内容放入某个文本文件时,它似乎添加了一些垃圾字符。例如,我正在用字符串编写一个实用程序名称,并将该字符串复制到文件中,如下所示

$CodeCount+="ccount.exe"

$CodeCount | Out-file "C:\CodeCount.bat"
当我执行这个批处理文件时,它失败了,因为它前面显示了一些垃圾字符

即使我尝试使用trim(),但结果仍然相同


如何避免在前面添加垃圾字符?

这是因为
输出文件所使用的标准编码是
Unicode
,它在文件的开头添加了一些BOM值(使用十六进制编辑器打开文件时可以看到这些值)。要避免这些字节,请使用
-编码ASCII

$CodeCount | Out-file -encoding ascii "C:\CodeCount.bat"

至少在默认格式中不要使用
输出文件
。使用
设置内容
。或者显式地在
out file
中设置编码,类似于
out file-encoding ascii
。Out文件默认使用utf16(实际上是ucs-2)编码,在许多应用程序(包括Hg、Git等版本控制系统)中不会被视为纯文本,并添加您提到的“有趣”字符


请注意,重定向
与输出文件相同,并将提供相同的结果。

输出文件的默认编码为Little-Endian Unicode
cmd.exe
与此编码不兼容,因此只需使用
ASCII

$CodeCount | Out-file -encoding ascii "C:\CodeCount.bat"

输出文件-编码ASCII

尝试
输出文件-编码ASCII