Question: When I execute the following simple script in PowerShell 7.1, I get the (correct) value of 3, regardless of whether the script's encoding is Latin1 or UTF8.

```
'Bär'.length

```

This surprises me because I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8.

Because both scripts evaluate the expression to 3, I am forced to conclude that PowerShell 7.1 applies some heuristic method to infer a Script's encoding when executing it.

Is my conclusion correct and is this documented somewhere?

Answer: 
The encoding is unrelated to this case: you are calling `string.Length` which is documented to return the number of UTF-16 code units. This roughly correlates to letters (when you ignore combining characters and high codepoints like emoji)

Encoding only comes into play when converting implicitly or explicitly to/from a byte array, file, or p/invoke. It doesn’t affect how .Net stores the data backing a string.

Speaking to the encoding for PS1 files, that is dependent upon version. Older versions have a fallback encoding of `Encoding.ASCII`, but will respect a BOM for UTF-16 or UTF-8. Newer versions use UTF-8 as the fallback.

In at least 5.1.19041.1, loading the file `'Bär'.Length` (`27 42 C3 A4 72 27 2E 4C 65 6E 67 74 68`) and running it with `. .\Bar.ps1` will result in 4 printing.

If the same file is saved as Windows-1252 (`27 42 E4 72 27 2E 4C 65 6E 67 74 68`), then it will print 3.

tl;dr: `string.Length` always returns number of UTF-16 code units. PS1 files should be in UTF-8 with BOM for cross version compatibility.
I think without a BOM, PS 5 assumes ansi or windows-1252, while PS 7 assumes utf8 no bom. This file saved as ansi in notepad works in PS 5 but not perfectly in PS 7. Just like a utf8 no bom file with special characters wouldn't work perfectly in PS 5. A utf16 ps1 file would always have a BOM or encoding signature. A powershell string in memory would always be utf16, but a character is considered to have a length of 1 except for emoji's. If you have emacs, esc-x hexl-mode is a nice way to look at it.

```
'¿Cómo estás?'

```

```
 format-hex file.ps1

   Label: C:\Users\js\foo\file.ps1

          Offset Bytes                                           Ascii
                 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
          ------ ----------------------------------------------- -----
0000000000000000 27 BF 43 F3 6D 6F 20 65 73 74 E1 73 3F 27 0D 0A '¿Cómo estás?'��

```