The following situation:
- PowerShell script creates a UTF-8 encoded file
- The user may or may not edit the file, possibly losing the specification, but must save the encoding as UTF-8 and possibly change the line separators
- The same PowerShell script reads the file, adds some more content and writes all of it as UTF-8 back to the same file
- This can be repeated many times.
With Get-Content and Out-File -Encoding UTF8 , I have trouble reading it. He stumbled upon a specification that he had written earlier (putting it in the content, breaking my parsing regular expression), doesn't use UTF-8 encoding, and even removes line breaks in the original part of the content.
I need a function that can read any UTF-8 encoded file, ignore and delete the specification, and not modify the contents. What should i use?
Update
I added a small test script that shows what I'm trying to do and what happens instead.
# Read data if exists $data = "" $startRev = 1; if (Test-Path test.txt) { $data = Get-Content -Path test.txt if ($data -match "^[0-9-]{10} - r([0-9]+)") { $startRev = [int]$matches[1] + 1 } } Write-Host Next revision is $startRev
After starting several times, new sections should be added to the beginning of the file, existing content should not be changed in any way (it currently loses line breaks), and no additional new lines should be added at the end of the file (it seems to happen sometimes) .
Instead, a second run causes an error.
encoding powershell utf-8
ygoe
source share