Powershell Out-File: 强制编码为Ascii

4
我将尝试使用 Powershell 规范化一组制表符分隔的日志文件。
以下是当前的脚本:
(Get-ChildItem *.csv) |%{
#Store the name of the file & date
$Name = $_.basename
$FileDate = $_.CreationTime
#Prepends the following to each message: unique Identifer, Hostname, date
(Get-Content $_.fullname) -replace "^","AR-LOG|$Name|$FileDate|"|
#Replaces the TAB delimeter with a Pipe delimeter
Foreach-Object {$_ -replace '   ','|'}  |
#Appends the resulting message in ascii
Out-File -append -FilePath normalized.log -Encoding ascii

这里可以看到输入和输出的一部分:

http://pastebin.com/uaQadYUC

我如何强制输出文件为ascii而不是某种unicode类型?

*** 编辑:进一步研究发现输入文件实际上是windows-1252编码,Get-Content似乎无法本地处理(?)

3个回答

6
你应该能够在... | Out-File -encoding ascii myfile.txt中使用编码标志。如果你使用了append,请确保所有的附加都使用相同的编码,否则你将得到一个无法使用的文件。

1
是的,这就是我在脚本中所做的(您可以看到),但似乎没有起作用。 - Josh Brower
不工作,如果字符串本身是utf8。 - undefined

3
将文件格式从 ASCII 改为 UTF8$filename = "c:\docs\demo.csv" (Get-Content $filename) | Set-Content $filename -Encoding UTF8

0

你能试着使用ReadAllText方法吗?它将整个文件存储在一个字符串中。Get-Content将值存储为字符串数组,其中数组值是文件的一行。

(Get-ChildItem *.csv) |%{
#Store the name of the file & date
$Name = $_.basename
$FileDate = $_.CreationTime
#Prepends the following to each message: unique Identifer, Hostname, date
([IO.File]::ReadAllText($_.fullname)) -replace "^","AR-LOG|$Name|$FileDate|"
#Replaces the TAB delimeter with a Pipe delimeter
-replace '   ','|'  |
#Appends the resulting message in ascii
Out-File -append -FilePath normalized.log -Encoding ascii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接