【问题标题】:Powershell Out-File: Force encoding to AsciiPowershell Out-File:强制编码为 Ascii
【发布时间】:2019-12-09 22:26:41
【问题描述】:

我正在尝试使用 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

输入和输出的sn-p可以在这里看到:

http://pastebin.com/uaQadYUC

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

***编辑:进一步的故障排除显示输入文件实际上是 windows-1252 编码的,显然 Get-Content 无法本地处理(?)

【问题讨论】:

    标签: powershell character-encoding


    【解决方案1】:

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

    【讨论】:

    • 是的,这就是我在脚本中所做的(你可以看到),但它似乎不起作用。
    【解决方案2】:

    将文件格式从ASCII更改为UTF8

    $filename = "c:\docs\demo.csv" (Get-Content $filename) | Set-Content $filename -Encoding UTF8

    【讨论】:

      【解决方案3】:

      你可以玩一下 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
      

      【讨论】:

        猜你喜欢
        • 2012-07-03
        • 2014-04-04
        • 2023-02-02
        • 2023-02-24
        • 2014-10-29
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多