在PowerShell中以二进制模式读取.dat文件,以避免将特殊字符转换为垃圾字符

时间:2019-03-04 12:57:28

标签: powershell filereader

我想在Powershell中将.dat文件读取为二进制流。由于我是Powershell的新手,因此无法弄清楚该如何做。 在将文件作为二进制流读取并且要用LF替换二进制CRLF字符之后。

1 个答案:

答案 0 :(得分:0)

您可以使用.Net $bytes = [System.IO.File]::ReadAllBytes("<YOUR FILE>")或Powershell $bytes = Get-Content -Path "<YOUR FILE>" -Encoding Byte -Raw读取二进制数据作为字节数组(System.Byte[])。

如果使用$text = [System.Text.Encoding]::ASCII.GetString($bytes)将其转换为ASCII字符串,则应该可以将CRLF替换为LF。

类似这样的东西:

# read the binary data as byte array
$bytes = [System.IO.File]::ReadAllBytes("<YOUR FILE>")
# convert to ASCII string
$text = [System.Text.Encoding]::ASCII.GetString($bytes)

# replace the CRLF to LF
$text = $text -replace "`r`n", "`n"

# convert back to byte array
$bytes = [System.Text.Encoding]::ASCII.GetBytes($text)