Encoding file names windows

Содержание
  1. Choose text encoding when you open and save files
  2. What do you want to do?
  3. Understand text encoding
  4. Different encoding standards for different alphabets
  5. Unicode: One encoding standard for many alphabets
  6. Choose an encoding standard when you open a file
  7. Choose an encoding standard when you save a file
  8. Choose an encoding standard
  9. Look up encoding standards that are available in Word
  10. Основные сведения о кодировке файлов в VS Code и PowerShell Understanding file encoding in VS Code and PowerShell
  11. Что такое кодировка и почему она важна? What is file encoding and why is it important?
  12. Распространенные причины проблемы с кодировкой Common causes of encoding issues
  13. Как определить наличие проблемы с кодировкой How to tell when you have encoding issues
  14. Взаимодействие расширения PowerShell для VS Code с кодировками How the PowerShell extension in VS Code interacts with encodings
  15. Выбор подходящей кодировки Choosing the right encoding
  16. Настройка VS Code Configuring VS Code
  17. Настройка PowerShell Configuring PowerShell
  18. Существующие скрипты Existing scripts
  19. Интегрированная среда сценариев (ISE) PowerShell The PowerShell Integrated Scripting Environment (ISE)
  20. Система управления версиями Source control software
  21. Среды других участников Collaborators’ environments
  22. Другие программы Other programs
  23. Другие ресурсы о кодировках в PowerShell Other resources on encoding in PowerShell

Choose text encoding when you open and save files

Typically, you can share text files without worrying about the underlying details of how the text is stored. However, if you share text files with people who work in other languages, download text files across the Internet, or share text files with other computer systems, you may need to choose an encoding standard when you open or save a file.

When you or someone else opens a text file in Microsoft Word or in another program — perhaps on a computer that has system software in a language that is different from the language that was used to create the file — the encoding standard helps that program determine how to represent the text so that it is readable.

What do you want to do?

Understand text encoding

What appears to you as text on the screen is actually stored as numeric values in the text file. Your computer translates the numeric values into visible characters. It does this is by using an encoding standard.

An encoding standard is a numbering scheme that assigns each text character in a character set to a numeric value. A character set can include alphabetical characters, numbers, and other symbols. Different languages commonly consist of different sets of characters, so many different encoding standards exist to represent the character sets that are used in different languages.

Different encoding standards for different alphabets

The encoding standard that is saved with a text file provides the information that your computer needs to display the text on the screen. For example, in the Cyrillic (Windows) encoding, the character Й has the numeric value 201. When you open a file that contains this character on a computer that uses the Cyrillic (Windows) encoding, the computer reads the 201 numeric value and displays Й on the screen.

However, if you open the same file on a computer that uses a different encoding, the computer displays whatever character corresponds to the 201 numeric value in the encoding standard that the computer uses by default. For example, if your computer uses the Western European (Windows) encoding standard, the character in the original Cyrillic-based file will be displayed as É rather than Й because in Western European (Windows) encoding, the value 201 maps to É.

Unicode: One encoding standard for many alphabets

To avoid problems with encoding and decoding text files, you can save files with Unicode encoding. Unicode accommodates most characters sets across all the languages that are commonly used among computer users today.

Because Word is based on Unicode, Word automatically saves files encoded as Unicode. You can open and read Unicode-encoded files on your English-language computer system regardless of the language of the text. Likewise, when you use your English-language system to save files encoded as Unicode, the file can include characters not found in Western European alphabets, such as Greek, Cyrillic, Arabic, or Japanese characters.

Choose an encoding standard when you open a file

If, when you open a file, text appears garbled or as question marks or boxes, Word may not have accurately detected the encoding standard of text in the file. You can specify the encoding standard that you can use to display (decode) the text.

Click the File tab.

Scroll to the General section, and then select the Confirm file format conversion on open check box.

Note: When this check box is selected, Word displays the Convert File dialog box every time you open a file in a format other than a Word format (Word formats include .doc, .dot, .docx, .docm, .dotx, or .dotm files). If you frequently work with such files but rarely want to choose an encoding standard, remember to switch this option off to prevent having this dialog box open unnecessarily.

Close and then reopen the file.

In the Convert File dialog box, select Encoded Text.

In the File Conversion dialog box, select Other encoding, and then select the encoding standard that you want from the list.

You can preview the text in the Preview area to check whether all the text is readable in the encoding standard that you selected.

If almost all the text looks the same (for example, all boxes or all dots), the font required for displaying the characters may not be installed. If the font that you need is not available, you can install additional fonts.

To install additional fonts, do the following:

In Microsoft Windows, click the Start button, and then click Control Panel.

Do one of the following:

In Control Panel, click Uninstall a program.

In the list of programs, click the listing for Microsoft Office or Microsoft Word, depending on whether you installed Word as part of Office or as an individual program, and then click Change.

In Windows Vista

In Control Panel, click Uninstall a program.

In the list of programs, click the listing for Microsoft Office or Microsoft Word, depending on whether you installed Word as part of Office or as an individual program, and then click Change.

In Microsoft Windows XP

In Control Panel, click Add or Remove Programs.

In the Currently installed programs box, click the listing for Microsoft Office or Microsoft Word, depending on whether you installed Word as part of Office or as an individual program, and then click Change.

Under Change your installation of Microsoft Office, click Add or Remove Features, and then click Continue.

Under Installation Options, expand Office Shared Features, and then expand International Support.

Select the font set that you need, click the arrow next to your selection, and then select Run from My Computer.

Tip: When you open an encoded text file, Word applies the fonts that are defined in the Web Options dialog box. (To reach the Web Options dialog box, click the Microsoft Office Button, click Word Options, and then click Advanced. In the General section, click Web Options.) You can select the options on the Fonts tab in the Web Options dialog box to customize the font for each character set.

Choose an encoding standard when you save a file

If you don’t choose an encoding standard when you save a file, Word encodes the file as Unicode. Usually, you can use the default Unicode encoding, because it supports most characters in most languages.

If your document will be opened in a program that does not support Unicode, you can choose an encoding standard that matches that of the target program. For example, Unicode enables you to create a Traditional Chinese language document on your English-language system. However, if the document will be opened in a Traditional Chinese language program that does not support Unicode, you can save the document with Chinese Traditional (Big5) encoding. When the document is opened in the Traditional Chinese language program, all the text is displayed properly.

Читайте также:  Драйвер для принтера hp deskjet 2050a для windows 10

Note: Because Unicode is the most comprehensive standard, saving text in any other encoding may result in some characters that can no longer be displayed. For example, a document encoded in Unicode can contain Hebrew and Cyrillic text. If this document is saved with Cyrillic (Windows) encoding, the Hebrew text can no longer be displayed, and if the document is saved with Hebrew (Windows) encoding, the Cyrillic text can no longer be displayed.

If you choose an encoding standard that doesn’t support the characters you used in the file, Word marks in red the characters that it cannot save. You can preview the text in the encoding standard that you choose before you save the file.

Text formatted in the Symbol font or in field codes is removed from the file when you save a file as encoded text.

Choose an encoding standard

Click the File tab.

If you want to save the file in a different folder, locate and open the folder.

In the File name box, type a new name for the file.

In the Save as type box, select Plain Text.

If the Microsoft Office Word Compatibility Checker dialog box appears, click Continue.

In the File Conversion dialog box, select the option for the encoding standard that you want to use:

To use the default encoding standard for your system, click Windows (Default).

To use the MS-DOS encoding standard, click MS-DOS.

To choose a specific encoding standard, click Other encoding, and then select the encoding standard that you want from the list. You can preview the text in the Preview area to check whether all the text is readable in the encoding standard that you selected.

Note: You can resize the File Conversion dialog box so that you can preview more of your document.

If you receive a message that states, «Text marked in red will not save correctly in the chosen encoding,» you can try to choose a different encoding, or you can select the Allow character substitution check box.

When you allow character substitution, Word replaces a character that cannot be displayed with the closest equivalent character in the encoding that you chose. For example, three dots replace an ellipsis, and straight quotation marks replace curly quotation marks.

If the encoding that you chose has no equivalent character for a character marked in red, the character marked in red will be saved as an out-of-context character, such as a question mark.

If the document will be opened in a program that does not wrap text from one line to the next, you can include hard line breaks in the document by selecting the Insert line breaks check box, and then specifying whether you want the line breaks to be delineated with a carriage return (CR), line feed (LF), or both, in the End lines with box.

Look up encoding standards that are available in Word

Word recognizes several encoding standards, and it supports the encoding standards that are provided with the system software on your computer.

The following list of writing systems shows the encoding standards (also called code pages) associated with each writing system.

Unicode (UCS-2 little-endian and big-endian, UTF-8, UTF-7)

Default font based on the Normal style for your language version of Word

Windows 1256, ASMO 708

GB2312, GBK, EUC-CN, ISO-2022-CN, HZ

BIG5, EUC-TW, ISO-2022-TW

Windows 1251, KOI8-R, KOI8-RU, ISO8859-5, DOS 866

English, Western European, or other Latin script

Основные сведения о кодировке файлов в VS Code и PowerShell Understanding file encoding in VS Code and PowerShell

При использовании VS Code для создания и редактирования сценариев PowerShell очень важно, чтобы ваши файлы сохранялись в правильной кодировке символов. When using VS Code to create and edit PowerShell scripts, it is important that your files are saved using the correct character encoding format.

Что такое кодировка и почему она важна? What is file encoding and why is it important?

VS Code управляет интерфейсом ввода строки символов в буфер пользователем и чтения-записи блоков байтов в файловой системе. VS Code manages the interface between a human entering strings of characters into a buffer and reading/writing blocks of bytes to the filesystem. При сохранении файла в VS Code используется кодирование текста для определения того, какие байты получит каждый символ. When VS Code saves a file, it uses a text encoding to decide what bytes each character becomes. Подробные сведения см. в статье О шифровании символов. For more information, see about_Character_Encoding.

Аналогичным образом, когда оболочка PowerShell запускает скрипт, ей необходимо преобразовать байты из файла в символы для преобразования файла в программу PowerShell. Similarly, when PowerShell runs a script it must convert the bytes in a file to characters to reconstruct the file into a PowerShell program. Так как VS Code записывает файл, а PowerShell считывает файл, этим средствам необходимо использовать одну и ту же систему кодировки. Since VS Code writes the file and PowerShell reads the file, they need to use the same encoding system. Этот процесс синтаксического анализа скрипта PowerShell идет так: байты -> символы -> лексемы -> дерево абстрактного синтаксиса -> выполнение. This process of parsing a PowerShell script goes: bytes -> characters -> tokens -> abstract syntax tree -> execution.

И VS Code, и PowerShell устанавливаются с подходящей конфигурацией кодировки по умолчанию. Both VS Code and PowerShell are installed with a sensible default encoding configuration. Тем не менее кодировка по умолчанию, используемая PowerShell, была изменена с выпуском PowerShell Core (версии 6.x). However, the default encoding used by PowerShell has changed with the release of PowerShell Core (v6.x). Чтобы избежать проблем с PowerShell и расширениями PowerShell в VS Code, необходимо настроить параметры VS Code и PowerShell должным образом. To ensure you have no problems using PowerShell or the PowerShell extension in VS Code, you need to configure your VS Code and PowerShell settings properly.

Распространенные причины проблемы с кодировкой Common causes of encoding issues

Проблемы с кодировкой возникают, если кодировка VS Code в целом или вашего файла скрипта не совпадает с кодировкой, ожидаемой в PowerShell. Encoding problems occur when the encoding of VS Code or your script file does not match the expected encoding of PowerShell. В PowerShell нет способа автоматически определить кодировку файла. There is no way for PowerShell to automatically determine the file encoding.

Проблемы с кодировкой более вероятны при использовании символов не из 7-разрядной кодировки ASCII. You’re more likely to have encoding problems when you’re using characters not in the 7-bit ASCII character set. Пример: For example:

  • Расширенные небуквенные символы, такие как длинное тире ( — ), неразрывный пробел ( ) или левая двойная кавычка ( » ). Extended non-letter characters like em-dash ( — ), non-breaking space ( ) or left double quotation mark ( » )
  • Латинские символы с диакритикой ( É , ü ) Accented latin characters ( É , ü )
  • Нелатинские символы, такие как кириллица ( Д , Ц ) Non-latin characters like Cyrillic ( Д , Ц )
  • Символы иероглифического письма ( 本 , 화 , が ). CJK characters ( 本 , 화 , が )

Распространенные причины проблем с кодировкой: Common reasons for encoding issues are:

  • Параметры кодировок по умолчанию VS Code и PowerShell не были изменены. The encodings of VS Code and PowerShell have not been changed from their defaults. В версиях до PowerShell 5.1 (включительно) кодировка по умолчанию отличается от используемой в VS Code. For PowerShell 5.1 and below, the default encoding is different from VS Code’s.
  • Открыт другой редактор, и файл перезаписан в новой кодировке. Another editor has opened and overwritten the file in a new encoding. Это часто происходит с интегрированной средой сценариев. This often happens with the ISE.
  • Файл возвращается в систему управления версиями в кодировке, отличающейся от той, которая ожидается в VS Code или PowerShell. The file is checked into source control in an encoding that is different from what VS Code or PowerShell expects. Это может произойти, когда участники совместной работы используют редакторы с различными конфигурациями кодировок. This can happen when collaborators use editors with different encoding configurations.
Читайте также:  Vps hosting with windows

Как определить наличие проблемы с кодировкой How to tell when you have encoding issues

Часто ошибки кодирования в скриптах представляются как ошибки синтаксического анализа. Often encoding errors present themselves as parse errors in scripts. Если вы видите странные последовательности символов в скрипте, это может быть проблемой. If you find strange character sequences in your script, this can be the problem. В примере ниже тире ( – ) отображается в виде символов ※ : In the example below, an en-dash ( – ) appears as the characters ※ :

Эта проблема возникает, так как VS Code кодирует символ – в UTF-8 как байты 0xE2 0x80 0x93 . This problem occurs because VS Code encodes the character – in UTF-8 as the bytes 0xE2 0x80 0x93 . Если эти байты декодируются в кодировке Windows-1252, они интерпретируются как символы ※ . When these bytes are decoded as Windows-1252, they are interpreted as the characters ※ .

Некоторые странные последовательности символов, которые можно видеть: Some strange character sequences that you might see include:

  • ※ вместо – . ※ instead of –
  • ※ вместо — . ※ instead of —
  • Ä2 вместо Ä . Ä2 instead of Ä
  • Â вместо (неразрывный пробел); Â instead of (a non-breaking space)
  • é вместо é . é instead of é

Этот удобный справочник перечисляет распространенные шаблоны, которые указывают на проблему между кодировками UTF-8 и Windows-1252. This handy reference lists the common patterns that indicate a UTF-8/Windows-1252 encoding problem.

Взаимодействие расширения PowerShell для VS Code с кодировками How the PowerShell extension in VS Code interacts with encodings

Расширение PowerShell взаимодействует со скриптами несколькими способами: The PowerShell extension interacts with scripts in a number of ways:

  1. При изменении скриптов в VS Code содержимое отправляется из VS Code в расширение. When scripts are edited in VS Code, the contents are sent by VS Code to the extension. Протокол языкового сервера требует, чтобы это содержимое передавалось в UTF-8. The Language Server Protocol mandates that this content is transferred in UTF-8. Таким образом, расширение не сможет получить неправильную кодировку. Therefore, it is not possible for the extension to get the wrong encoding.
  2. При выполнении скриптов в интегрированной консоли они считываются оболочкой PowerShell непосредственно из файла. When scripts are executed directly in the Integrated Console, they’re read from the file by PowerShell directly. Если кодировка PowerShell отличается от кодировки VS Code, может произойти сбой. If PowerShell’s encoding differs from VS Code’s, something can go wrong here.
  3. Когда скрипт, который открыт в VS Code, ссылается на другой скрипт, который не был открыт в VS Code, расширение загружает содержимое второго скрипта из файловой системы. When a script that is open in VS Code references another script that is not open in VS Code, the extension falls back to loading that script’s content from the file system. Расширение PowerShell по умолчанию использует кодировку UTF-8, но при этом применяет обнаружение метки порядка байтов (BOM), чтобы выбрать правильную кодировку. The PowerShell extension defaults to UTF-8 encoding, but uses byte-order mark, or BOM, detection to select the correct encoding.

Проблема возникает при предположении кодировки, не использующей BOM (такой как UTF-8 без метки порядка байтов или Windows-1252). The problem occurs when assuming the encoding of BOM-less formats (like UTF-8 with no BOM and Windows-1252). Расширение PowerShell по умолчанию использует UTF-8. The PowerShell extension defaults to UTF-8. Расширение не может изменить параметры кодировки в VS Code. The extension cannot change VS Code’s encoding settings. Дополнительные сведения см. в разделе Проблема № 824. For more information, see issue #824.

Выбор подходящей кодировки Choosing the right encoding

Различные системы и приложения могут использовать различные кодировки: Different systems and applications can use different encodings:

  • В .NET Standard, в Интернете и в среде Linux теперь в основном используется кодировка UTF-8. In .NET Standard, on the web, and in the Linux world, UTF-8 is now the dominant encoding.
  • Во многих приложениях .NET Framework используется UTF-16. Many .NET Framework applications use UTF-16. По историческим причинам ее иногда называют «Юникод»; сейчас этот термин относится к более широкому стандарту, охватывающему UTF-8 и UTF-16. For historical reasons, this is sometimes called «Unicode», a term that now refers to a broad standard that includes both UTF-8 and UTF-16.
  • В Windows многие приложения, которые были созданы еще до распространения Юникода, по-прежнему могут по умолчанию использовать Windows-1252. On Windows, many native applications that predate Unicode continue to use Windows-1252 by default.

Кодировки Юникода также используют понятие метки порядка следования байтов (BOM). Unicode encodings also have the concept of a byte-order mark (BOM). BOM ставится в начале текста, чтобы декодер мог определить, какая кодировка используется в тексте. BOMs occur at the beginning of text to tell a decoder which encoding the text is using. Для многобайтовых кодировок BOM также указывает порядок следования байтов кодировки. For multi-byte encodings, the BOM also indicates endianness of the encoding. BOM представляются байтами, которые редко встречаются в тексте в Юникоде. Это позволяет сделать обоснованное предположение, что текст записан в Юникоде, если присутствует метка BOM. BOMs are designed to be bytes that rarely occur in non-Unicode text, allowing a reasonable guess that text is Unicode when a BOM is present.

BOM не являются обязательными; в мире Linux они не так популярны, поскольку во всех прочих местах используется надежное соглашение UTF-8. BOMs are optional and their adoption isn’t as popular in the Linux world because a dependable convention of UTF-8 is used everywhere. Большинство приложений Linux предполагают, что текстовый ввод кодируется в UTF-8. Most Linux applications presume that text input is encoded in UTF-8. Хотя многие приложения Linux могут распознавать и правильно обрабатывать BOM, некоторые этого не делают, что приводит к появлению артефактов в тексте, открываемом с помощью этих приложений. While many Linux applications will recognize and correctly handle a BOM, a number do not, leading to artifacts in text manipulated with those applications.

Таким образом : Therefore :

  • Если вы работаете в основном с приложениями Windows и Windows PowerShell, следует предпочтительно использовать такие кодировки, как UTF-8 с BOM или UTF-16. If you work primarily with Windows applications and Windows PowerShell, you should prefer an encoding like UTF-8 with BOM or UTF-16.
  • Если вы работаете на разных платформах, следует отдавать предпочтение UTF-8 с BOM. If you work across platforms, you should prefer UTF-8 with BOM.
  • Если вы работаете главным образом в контексте Linux, следует отдавать предпочтение UTF-8 без BOM. If you work mainly in Linux-associated contexts, you should prefer UTF-8 without BOM.
  • Windows-1252 и latin-1 — устаревшие кодировки, которых по возможности следует избегать. Windows-1252 and latin-1 are essentially legacy encodings that you should avoid if possible. Тем не менее некоторые приложения предыдущих версий в Windows зависят от их. However, some older Windows applications may depend on them.
  • Также стоит отметить, что подписывание скриптов зависит от кодировки, то есть изменение кодировки в подписанном скрипте потребует повторного подписывания. It’s also worth noting that script signing is encoding-dependent, meaning a change of encoding on a signed script will require resigning.

Настройка VS Code Configuring VS Code

Кодировка VS Code по умолчанию — UTF-8 без метки порядка байтов. VS Code’s default encoding is UTF-8 without BOM.

Чтобы задать Кодировка в VS Code, перейдите к параметрам VS Code ( CTRL + , ) и задайте параметр «files.encoding» : To set VS Code’s encoding, go to the VS Code settings ( Ctrl + , ) and set the «files.encoding» setting:

Возможны следующие значения: Some possible values are:

  • utf8 : UTF-8 без метки порядка байтов utf8 : UTF-8 without BOM
  • utf8bom : UTF-8 с меткой порядка байтов utf8bom : UTF-8 with BOM
  • utf16le : UTF-16 с прямым порядком байтов utf16le : Little endian UTF-16
  • utf16be : UTF-16 с обратным порядком байтов utf16be : Big endian UTF-16
  • windows1252 : Windows-1252 windows1252 : Windows-1252

Должен отобразиться раскрывающийся список представления графического пользовательского интерфейса или дополнение в представлении JSON. You should get a dropdown for this in the GUI view, or completions for it in the JSON view.

Читайте также:  Windows 2012 server r2 создание образа системы windows

Чтобы обеспечить автоматическое определение кодировки, если это возможно, можно также добавить следующее: You can also add the following to autodetect encoding when possible:

Если вы не хотите, чтобы эти параметры влияли на все типы файлов, в VS Code можно задавать конфигурации для каждого языка отдельно. If you don’t want these settings to affect all files types, VS Code also allows per-language configurations. Создать параметр для конкретного языка можно, поместив параметры в поле [ ] . Create a language-specific setting by putting settings in a [ ] field. Пример: For example:

Вы также можете установить [средство отслеживания Gremlins][] для Visual Studio Code. You may also want to consider installing the Gremlins tracker for Visual Studio Code. Это расширение раскрывает определенные символы Юникода, которые могут быть легко повреждены из-за своей невидимости или схожести с другими обычными символами. This extension reveals certain Unicode characters that easily corrupted because they are invisible or look like other normal characters.

Настройка PowerShell Configuring PowerShell

В PowerShell кодировка по умолчанию зависит от версии: PowerShell’s default encoding varies depending on version:

  • В PowerShell 6+ кодировка по умолчанию на всех платформах — UTF-8 без метки порядка байтов. In PowerShell 6+, the default encoding is UTF-8 without BOM on all platforms.
  • В Windows PowerShell кодировка по умолчанию — обычно Windows-1252, расширение latin-1, которое также называется ISO 8859-1. In Windows PowerShell, the default encoding is usually Windows-1252, an extension of latin-1, also known as ISO 8859-1.

В PowerShell 5 + можно определить кодировку по умолчанию так: In PowerShell 5+ you can find your default encoding with this:

Следующий скрипт может использоваться для определения кодировки, которую ваш сеанс PowerShell выводит для скрипта, где нет метки порядка байтов. The following script can be used to determine what encoding your PowerShell session infers for a script without a BOM.

Можно настроить PowerShell так, чтобы использовать заданную кодировку в более общем виде с помощью параметров профиля. It’s possible to configure PowerShell to use a given encoding more generally using profile settings. См. следующие статьи: See the following articles:

Заставить PowerShell использовать конкретную кодировку для входных данных невозможно. It’s not possible to force PowerShell to use a specific input encoding. В PowerShell 5.1 и более ранних версий в Windows с языковым стандартом en-US по умолчанию используется кодировка Windows-1252, если отсутствует метка порядка байтов. PowerShell 5.1 and below, running on Windows with the locale set to en-US, defaults to Windows-1252 encoding when there’s no BOM. Другие параметры языкового стандарта могут использовать другую кодировку. Other locale settings may use a different encoding. Для обеспечения совместимости лучше сохранять скрипты в Юникоде с меткой порядка байтов. To ensure interoperability, it’s best to save scripts in a Unicode format with a BOM.

Любые другие имеющиеся у вас инструменты для работы со скриптами PowerShell могут зависеть от выбранных параметров кодировки или преобразовывать скрипты в другую кодировку. Any other tools you have that touch PowerShell scripts may be affected by your encoding choices or re-encode your scripts to another encoding.

Существующие скрипты Existing scripts

Скрипты, которые уже находятся в файловой системе, могут нуждаться в повторном кодировании в указанную вами кодировку. Scripts already on the file system may need to be re-encoded to your new chosen encoding. В нижней строке VS Code вы увидите метку UTF-8. In the bottom bar of VS Code, you’ll see the label UTF-8. Щелкните ее, чтобы открыть панель действий, и выберите команду Сохранить с кодировкой. Click it to open the action bar and select Save with encoding. Теперь вы можете выбрать новую кодировку для этого файла. You can now pick a new encoding for that file. Подробные инструкции см. в разделе Кодировка в VS Code. See VS Code’s encoding for full instructions.

Если вам нужно повторно кодировать несколько файлов, можно использовать следующий скрипт: If you need to re-encode multiple files, you can use the following script:

Интегрированная среда сценариев (ISE) PowerShell The PowerShell Integrated Scripting Environment (ISE)

При редактировании скриптов с помощью интегрированной среды сценариев PowerShell необходимо синхронизировать здесь параметры кодировки. If you also edit scripts using the PowerShell ISE, you need to synchronize your encoding settings there.

Интегрированная среда сценариев должна учитывать метку порядка байтов, но можно также использовать отражение для задания кодировки. The ISE should honor a BOM, but it’s also possible to use reflection to set the encoding. Обратите внимание, что это значение не сохраняется между запусками. Note that this wouldn’t be persisted between startups.

Система управления версиями Source control software

Некоторые системы управления версиями, например git, игнорируют кодировки; git отслеживает только байты. Some source control tools, such as git, ignore encodings; git just tracks the bytes. Поведение других, например Azure DevOps или Mercurial, может отличаться. Others, like Azure DevOps or Mercurial, may not. Даже некоторые средства, основанные на git, полагаются на декодирование текста. Even some git-based tools rely on decoding text.

Если это так, убедитесь, что вы: When this is the case, make sure you:

  • Настроили кодировку в системе управления версиями в соответствии с вашей конфигурацией VS Code. Configure the text encoding in your source control to match your VS Code configuration.
  • Сделали так, что все файлы добавляются в систему управления версиями в соответствующей кодировке. Ensure all your files are checked into source control in the relevant encoding.
  • Остерегайтесь изменять кодировки, полученные через систему управления версиями. Be wary of changes to the encoding received through source control. Ключевым признаком здесь будет разностный файл, который указывает, что изменения отсутствуют (так как изменены байты, но не символы). A key sign of this is a diff indicating changes but where nothing seems to have changed (because bytes have but characters have not).

Среды других участников Collaborators’ environments

Настроив систему управления версиями, убедитесь также, что параметры других участников, работающих над теми файлами, к которым вы предоставляете общий доступ, не переопределяют кодировку путем повторного кодирования файлов PowerShell. On top of configuring source control, ensure that your collaborators on any files you share don’t have settings that override your encoding by re-encoding PowerShell files.

Другие программы Other programs

Все другие программы, которые считывают или записывают скрипты PowerShell, могут перекодировать их. Any other program that reads or writes a PowerShell script may re-encode it.

Некоторые примеры. Some examples are:

  • Использование буфера обмена для копирования и вставки скрипта. Using the clipboard to copy and paste a script. Такое часто встречается в следующих случаях: This is common in scenarios like:
    • Копирование скрипта в виртуальную машину. Copying a script into a VM
    • Копирование скрипта из электронной почты или с веб-страницы. Copying a script out of an email or webpage
    • Копирование скрипта через документ Microsoft Word или PowerPoint. Copying a script into or out of a Microsoft Word or PowerPoint document
  • Другие текстовые редакторы, например: Other text editors, such as:
    • Блокнот; Notepad
    • vim; vim
    • любой другой редактор скриптов PowerShell. Any other PowerShell script editor
  • Служебные программы редактирования текста, например: Text editing utilities, like:
    • Get-Content / Set-Content / Out-File
    • Операторы перенаправления PowerShell, такие как > и >> . PowerShell redirection operators like > and >>
    • sed / awk
  • Программы передачи файлов, такие как: File transfer programs, like:
    • Веб-браузер при скачивании скриптов. A web browser, when downloading scripts
    • Общий файловый ресурс. A file share

Некоторые из этих средств работают с байтами, а не с текстом, но другие позволяют настраивать кодировки. Some of these tools deal in bytes rather than text, but others offer encoding configurations. В случаях, когда необходимо настроить кодировку, используйте те же параметры, что и в вашем редакторе, чтобы предотвратить возникновение проблем. In those cases where you need to configure an encoding, you need to make it the same as your editor encoding to prevent problems.

Другие ресурсы о кодировках в PowerShell Other resources on encoding in PowerShell

Существует несколько других достойных публикаций на тему кодировок и настройки кодирования в PowerShell: There are a few other nice posts on encoding and configuring encoding in PowerShell that are worth a read:

Оцените статью