Powershell Out文件:强制编码为Ascii

Powershell Out文件:强制编码为Ascii,powershell,character-encoding,Powershell,Character Encoding,我正在尝试使用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 $_.full

我正在尝试使用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
此处可以看到输入和输出的片段:

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


***编辑:进一步的故障排除表明,输入文件实际上是windows-1252编码的,显然获取的内容无法以本机方式处理(?)

您应该能够在输出文件上使用编码标志,如
所示输出文件-编码ascii myfile.txt
。如果您使用的是
append
,请确保所有append都使用相同的编码,否则您将得到一个不可用的文件。

您可以使用ReadAllText方法吗?它将整个文件存储在一个字符串中。获取内容将值存储为字符串数组,其中数组值是文件的行

(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

将文件格式从
ASCII
更改为
UTF8

$filename=“c:\docs\demo.csv”

(获取内容$filename)|设置内容$filename-编码UTF8

是的,这就是我在脚本中所做的(您可以看到),但它似乎不起作用。