Powershell magnling ascii text

I get extra characters and strings when trying to modify host files. For example, this selection line does not accept anything, but the two files are different from each other:

get-content -Encoding ascii C:\Windows\system32\drivers\etc\hosts |
  select-string -Encoding ascii -notmatch "thereisnolinelikethis" |
  out-file -Encoding ascii c:\temp\testfile

PS C:\temp> (get-filehash C:\windows\system32\drivers\etc\hosts).hash
C54C246D2941F02083B85CE2774D271BD574F905BABE030CC1BB41A479A9420E

PS C:\temp> (Get-FileHash C:\temp\testfile).hash
AC6A1134C0892AD3C5530E58759A09C73D8E0E818EC867C9203B9B54E4B83566
+4
source share
3 answers

I can confirm that your commands inexplicably lead to additional line breaks in the output file, at the beginning and at the end. Powershell also converts tabs to the source file in four spaces.

So far, I can’t explain why these commands do the same thing without these problems:

Try using this code:

Get-Content -Path C:\Windows\System32\drivers\etc\hosts -Encoding Ascii | 
  Where-Object { -not $_.Contains("thereisnolinelikethis")  } |
  Out-File -FilePath "c:\temp\testfile" -Encoding Ascii
+2
source

, PowerShell F & O ( ). , Select-String MatchInfo. , . , /, . MatchInfo , ​​( ). Line , , ():

Get-Content C:\Windows\system32\drivers\etc\hosts |
    Select-String -notmatch "thereisnolinelikethis" |
    Foreach {$_.Line} |
    Out-File -Encoding ascii c:\temp\testfile

, ASCII . PowerShell Unicode.

, , Where-Object Select-String . - - , . Select-String () (MatchInfo).

+2

Out-FileAdds the ending NewLine ( "`r`n") to the file testfile.

C:\Windows\System32\drivers\etc\hosts does not contain the final new line out of the box, so you get another FileHash file


If you open the files with StreamReader, you will see that the base stream is different in length (due to the ending new line in the new file):

PS C:\> $Hosts = [System.IO.StreamReader]"C:\Windows\System32\drivers\etc\hosts"
PS C:\> $Tests = [System.IO.StreamReader]"C:\temp\testfile"
PS C:\> $Hosts.BaseStream.Length
822
PS C:\> $Tests.BaseStream.Length
824
PS C:\> $Tests.BaseStream.Position = 822; $Tests.Read(); $Tests.Read()
13
10

ASCII characters 13 ( 0x0D) and 10 ( 0x0A) correspond to [System.Environment]::NewLineeither CR + LF

0
source

Source: https://habr.com/ru/post/1599147/


All Articles