Powershell Visual Studio Code

Posted on  by 



PowerShell in Visual Studio Code. PowerShell is a task-based command-line shell and scripting language built on.NET, which provides a powerful toolset for administrators on any platform. The Microsoft PowerShell extension for Visual Studio Code provides rich language support and capabilities such as completions, definition tracking, and linting analysis for PowerShell versions 3, 4, 5, and 5.1 as. And then pick PowerShell. Then from the Command Palette (Ctrl+Shift+P), select. Python: Select Interpreter and pick one of the conda environments. When you now open a new terminal VSCode starts PowerShell and activates the selected environment. This is exactly what the Anaconda-Prompt does. The PowerShell extension defaults to UTF-8 encoding, but uses byte-order mark, or BOM, detection to select the correct encoding. The problem occurs when assuming the encoding of BOM-less formats (like UTF-8 with no BOM and Windows-1252). The PowerShell extension defaults to UTF-8. The extension cannot change VS Code's encoding settings.

I’ve used VSCode as my primary Powershell environment for over 3 years and have tried a lot of extensions and settings, and now is your turn to learn from my.

-->

When using VS Code to create and edit PowerShell scripts, it is important that your files are savedusing the correct character encoding format.

What is file encoding and why is it important?

Powershell Visual Studio Code

VS Code manages the interface between a human entering strings of characters into a buffer andreading/writing blocks of bytes to the filesystem. When VS Code saves a file, it uses a textencoding to decide what bytes each character becomes. For more information, seeabout_Character_Encoding.

Similarly, when PowerShell runs a script it must convert the bytes in a file to characters toreconstruct the file into a PowerShell program. Since VS Code writes the file and PowerShell readsthe file, they need to use the same encoding system. This process of parsing a PowerShell scriptgoes: bytes -> characters -> tokens -> abstract syntax tree -> execution.

Both VS Code and PowerShell are installed with a sensible default encoding configuration. However,the default encoding used by PowerShell has changed with the release of PowerShell Core (v6.x). Toensure you have no problems using PowerShell or the PowerShell extension in VS Code, you need toconfigure your VS Code and PowerShell settings properly.

Common causes of encoding issues

Encoding problems occur when the encoding of VS Code or your script file does not match the expectedencoding of PowerShell. There is no way for PowerShell to automatically determine the file encoding.

You're more likely to have encoding problems when you're using characters not in the7-bit ASCII character set. For example:

  • Extended non-letter characters like em-dash (), non-breaking space () or left doublequotation mark (')
  • Accented latin characters (É, ü)
  • Non-latin characters like Cyrillic (Д, Ц)
  • CJK characters (, , )

Common reasons for encoding issues are:

  • The encodings of VS Code and PowerShell have not been changed from their defaults. For PowerShell5.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 theISE.
  • The file is checked into source control in an encoding that is different from what VS Code orPowerShell expects. This can happen when collaborators use editors with different encodingconfigurations.

How to tell when you have encoding issues

Often encoding errors present themselves as parse errors in scripts. If you find strange charactersequences in your script, this can be the problem. In the example below, an en-dash () appears asthe characters â€':

This problem occurs because VS Code encodes the character in UTF-8 as the bytes0xE2 0x80 0x93. When these bytes are decoded as Windows-1252, they are interpreted as thecharacters â€'.

Some strange character sequences that you might see include:

  • â€' instead of
  • â€' instead of
  • Ä2 instead of Ä
  • Â instead of (a non-breaking space)
  • é instead of é

This handy reference lists the common patterns thatindicate a UTF-8/Windows-1252 encoding problem.

How the PowerShell extension in VS Code interacts with encodings

The PowerShell extension interacts with scripts in a number of ways:

  1. When scripts are edited in VS Code, the contents are sent by VS Code to the extension. TheLanguage Server Protocol mandates that this content is transferred in UTF-8. Therefore, it isnot possible for the extension to get the wrong encoding.
  2. When scripts are executed directly in the Integrated Console, they're read from the file byPowerShell directly. If PowerShell's encoding differs from VS Code's, something can go wronghere.
  3. When a script that is open in VS Code references another script that is not open in VS Code, theextension falls back to loading that script's content from the file system. The PowerShellextension defaults to UTF-8 encoding, but uses byte-order mark, or BOM, detection to selectthe correct encoding.

The problem occurs when assuming the encoding of BOM-less formats (like UTF-8 with no BOM andWindows-1252). The PowerShell extension defaults to UTF-8. The extension cannot change VS Code'sencoding settings. For more information, seeissue #824.

Choosing the right encoding

Different systems and applications can use different encodings:

  • In .NET Standard, on the web, and in the Linux world, UTF-8 is now the dominant encoding.
  • Many .NET Framework applications use UTF-16. For historical reasons, this is sometimes called'Unicode', a term that now refers to a broad standardthat includes both UTF-8 and UTF-16.
  • On Windows, many native applications that predate Unicode continue to use Windows-1252 by default.

Unicode encodings also have the concept of a byte-order mark (BOM). BOMs occur at the beginning oftext to tell a decoder which encoding the text is using. For multi-byte encodings, the BOM alsoindicates endianness of the encoding. BOMs are designedto be bytes that rarely occur in non-Unicode text, allowing a reasonable guess that text is Unicodewhen a BOM is present.

BOMs are optional and their adoption isn't as popular in the Linux world because a dependableconvention of UTF-8 is used everywhere. Most Linux applications presume that text input is encodedin UTF-8. 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:

  • If you work primarily with Windows applications and Windows PowerShell, you should prefer anencoding like UTF-8 with BOM or UTF-16.
  • If you work across platforms, you should prefer UTF-8 with BOM.
  • If you work mainly in Linux-associated contexts, you should prefer UTF-8 without BOM.
  • Windows-1252 and latin-1 are essentially legacy encodings that you should avoid if possible.However, some older Windows applications may depend on them.
  • It's also worth noting that script signing isencoding-dependent, meaning a change ofencoding on a signed script will require resigning.

Configuring VS Code

VS Code's default encoding is UTF-8 without BOM.

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 without BOM
  • utf8bom: UTF-8 with BOM
  • utf16le: Little endian UTF-16
  • utf16be: Big endian UTF-16
  • windows1252: Windows-1252

You should get a dropdown for this in the GUI view, or completions for it in the JSON view.

You can also add the following to autodetect encoding when possible:

If you don't want these settings to affect all files types, VS Code also allows per-languageconfigurations. Create a language-specific setting by putting settings in a [<language-name>]field. For example:

You may also want to consider installing the Gremlins tracker for Visual Studio Code. Thisextension reveals certain Unicode characters that easily corrupted because they are invisible orlook like other normal characters.

Configuring PowerShell

PowerShell's default encoding varies depending on version:

Visual
  • In PowerShell 6+, the default encoding is UTF-8 without BOM on all platforms.
  • In Windows PowerShell, the default encoding is usually Windows-1252, an extension of latin-1,also known as ISO 8859-1.

In PowerShell 5+ you can find your default encoding with this:

The following script can beused to determine what encoding your PowerShell session infers for a script without a BOM.

It's possible to configure PowerShell to use a given encoding more generally using profile settings.See the following articles:

  • @mklement0's answer about PowerShell encoding on StackOverflow.
  • @rkeithhill's blog post about dealing with BOM-less UTF-8 input in PowerShell.

It's not possible to force PowerShell to use a specific input encoding. PowerShell 5.1 and below,running on Windows with the locale set to en-US, defaults to Windows-1252 encoding when there's noBOM. Other locale settings may use a different encoding. To ensure interoperability, it's best tosave scripts in a Unicode format with a BOM.

Important

Any other tools you have that touch PowerShell scripts may be affected by your encoding choices orre-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. In thebottom bar of VS Code, you'll see the label UTF-8. Click it to open the action bar and select Savewith encoding. You can now pick a new encoding for that file. See VS Code's encoding for fullinstructions.

Powershell Visual Studio Code

If you need to re-encode multiple files, you can use the following script:

The PowerShell Integrated Scripting Environment (ISE)

If you also edit scripts using the PowerShell ISE, you need to synchronize your encodingsettings there.

The ISE should honor a BOM, but it's also possible to use reflection toset the encoding.Note that this wouldn't be persisted between startups.

Source control software

Some source control tools, such as git, ignore encodings; git just tracks the bytes. Others, likeAzure DevOps or Mercurial, may not. Even some git-based tools rely on decoding text.

Powershell visual studio code

When this is the case, make sure you:

  • 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 diffindicating changes but where nothing seems to have changed (because bytes have but characters havenot).

Collaborators' environments

On top of configuring source control, ensure that your collaborators on any files you share don'thave settings that override your encoding by re-encoding PowerShell files.

Other programs

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
    • Copying a script into or out of a Microsoft Word or PowerPoint document
  • Other text editors, such as:
    • Notepad
    • vim
    • Any other PowerShell script editor
  • Text editing utilities, like:
    • Get-Content/Set-Content/Out-File
    • 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. Inthose cases where you need to configure an encoding, you need to make it the same as your editorencoding to prevent problems.

Other resources on encoding in PowerShell

There are a few other nice posts on encoding and configuring encoding in PowerShell that are worth aread:

  • @mklement0's summary of PowerShell encoding on StackOverflow
  • Previous issues opened on VS Code-PowerShell for encoding problems:

PowerShell Core is the latest version of PowerShell, and is designed to run cross-platform on Windows, Mac, and Linux.

Powershell Visual Studio Code Download

Download the latest version of PowerShell Core that matches your installed operating system from https://github.com/PowerShell/PowerShell/releases taking note of any caveats.

Start Visual Studio Code.

Once loaded open the user settings.json file, via either:

  • use the key combination “CTRL and ,” or
  • press F1 and type settings or
  • via File menu, Preferences, Settings.

On the right hand side, between the { } section, enter the following information, to advise Visual Studio Code that you want to use PowerShell Core, and optionally also change the terminal.

If you already have lines in this file, it’s recommended to make a copy first for backup purposes, and you may also need to change the commas at the end of the lines to ensure that each setting line ends with a comma, apart from the last line.

// Specifies the full path to a PowerShell executable. Changes the installation of PowerShell used for language and debugging services. Select the relevant line that matches the installed OS, replacing version with the version installed.**

// On Windows:

// On Linux:

// On macOS:

// The path of the shell that the terminal uses. Select the relevant line that matches the installed OS.

// On Windows:

// On Linux:

// On macOS:

Example settings file that includes the lines above.

Save the settings.json file, then restart code.

To undo these changes, repeat the above but instead of adding the above lines, remove them, taking note to ensure the end of lines commas are matched up as above.

Powershell Visual Studio Code Download

Tip: PS core by default does not know about modules used by the default installation of PowerShell, so many cmdlets will not be available.

Powershell

To add these, modify the $env:psmodulepath to include:

You can either add these modules in the code, or by utilising PowerShell profiles. However, relying on profiles reduces code portability, and some developers prefer not to use profiles in order to reduce the risk of creating external dependencies that complicate running code on different machines.

Visual Studio Code Powershell Terminal

To use the profile option, add the following line to current PowerShell profile.

Powershell Visual Studio Code Debug

You can view the path to this file by typing $Profile into the powershell terminal at the bottom of the Visual Studio Code window.





Coments are closed