vs code скрипт подключения powershell
dimayakovlev.ru
В текущей версии Visual Studio Code 1.8.1 в качестве встроенного терминала, при использовании его в Microsoft Windows, по умолчанию используется интерпретатор комманд cmd.exe. Пользователям, знакомым с возможностями PowerShell, скорее всего, будет удобнее использовать в качестве встроенного терминала именно PowerShell, а не cmd.exe.
На этот случай Visual Studio Code не ограничивает пользователя в выборе используемого интерпретатора комманд, поэтому встроенный терминал может быть легко заменён на PowerShell. Для этого необходимо внести изменения в файл пользовательских настроек settings.json или, при желании внести изменения, затрагивающие только выбранную рабочую среду, в файл настроек этой рабочей среды:
Подробнее о настройке встроенного терминала можно прочитать в официальной документации Visual Studio Code здесь.
Другие заметки
Использование Grav CMS со встроенным веб-сервером PHP
Одной из полезных возможностей, добавленных в Grav CMS 1.1.10, стала поддержка работы системы управления контентом на встроенном веб-сервере PHP. Однако разработчики, использующие для запуска встроенного веб-сервера метод, описанный в заметке Удобный запуск встроенного веб-сервера PHP в Microsoft Windows, сталкиваются с проблемой.
Приведение значения переменной к типу Boolean в PHP
Приведение значения переменной к типу Boolean является распространённой задачей при разработке на языке PHP. Однако в ряде случаев, выполнения простого приведения типа может быть недостаточно.
dimayakovlev.ru © 2021 — Личная территория внутри всемирной паутины
Сайт создан и поддерживается мною с целью сохранения и распространения в свободном доступе опубликованных на нём материалов. Авторство разработок, текстов и изображений, принадлежит мне, если иное не указано отдельно.
При копировании материалов с сайта, не забывайте о важности обратных ссылок.
Размещение обратной индексируемой ссылки показывает интерес к содержанию сайта, что мотивирует к работе над новыми материалами.
Using Visual Studio Code for PowerShell Development
Visual Studio Code (VS Code) is a cross-platform script editor by Microsoft. Together with the PowerShell extension, it provides a rich and interactive script editing experience, making it easier to write reliable PowerShell scripts. Visual Studio Code with the PowerShell extension is the recommended editor for writing PowerShell scripts.
It supports the following PowerShell versions:
Visual Studio Code is not the same as Visual Studio.
Getting started
Before you begin, make sure PowerShell exists on your system. For modern workloads on Windows, macOS, and Linux, see the following links:
For traditional Windows PowerShell workloads, see Installing Windows PowerShell.
The Windows PowerShell ISE is still available for Windows. However, it is no longer in active feature development. The ISE only works with PowerShell 5.1 and older. As a component of Windows, it continues to be officially supported for security and high-priority servicing fixes. We have no plans to remove the ISE from Windows.
Install VS Code and the PowerShell Extension
Install Visual Studio Code. For more information, see the overview Setting up Visual Studio Code.
There are installation instructions for each platform:
Install the PowerShell Extension.
Installing the PowerShell Extension on Restricted Systems
Some systems are set up to require validation of all code signatures. You may receive the following error:
This problem can occur when PowerShell’s execution policy is set by Windows Group Policy. To manually approve PowerShell Editor Services and the PowerShell extension for VS Code, open a PowerShell prompt and run the following command:
You’re prompted with Do you want to run software from this untrusted publisher? Type A to run the file. Then, open VS Code and check that the PowerShell extension is functioning properly. If you still have problems getting started, let us know on GitHub issues.
Choosing a version of PowerShell to use with the extension
With PowerShell installing side-by-side with Windows PowerShell, it’s now possible to use a specific version of PowerShell with the PowerShell extension. This feature looks at a few well-known paths on different operating systems to discover installations of PowerShell.
Use the following steps to choose the version:
If you installed PowerShell to a non-typical location, it might not show up initially in the Session Menu. You can extend the session menu by adding your own custom paths as described below.
The PowerShell session menu can also be accessed from the green version number in the bottom right corner of status bar. Clicking this version number opens the session menu.
Configuration settings for Visual Studio Code
First, if you’re not familiar with how to change settings in VS Code, we recommend reading Visual Studio Code’s settings documentation.
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:
For more information about file encoding in VS Code, see Understanding file encoding. Also, check out How to replicate the ISE experience in VS Code for other tips on how to configure VS Code for PowerShell editing.
Adding your own PowerShell paths to the session menu
Add an item to the list powershell.powerShellAdditionalExePaths or create the list if it doesn’t exist in your settings.json :
Each item must have:
To set the default PowerShell version, set the value powershell.powerShellDefaultVersion to the text displayed in the session menu (also known as the versionName ):
If you open the session menu, you now see your additional PowerShell versions!
If you build PowerShell from source, this is a great way to test out your local build of PowerShell.
Debugging with Visual Studio Code
No-workspace debugging
In VS Code version 1.9 (or higher), you can debug PowerShell scripts without opening the folder that contains the PowerShell script.
You should see the Debug actions pane appear which allows you to break into the debugger, step, resume, and stop debugging.
Workspace debugging
Follow these steps to create a debug configuration file:
Click the create a launch.json file link.
From the Select Environment prompt, choose PowerShell.
Choose the type of debugging you’d like to use:
This file represents the common debug scenarios. When you open this file in the editor, you see an Add Configuration. button. You can click this button to add more PowerShell debug configurations. One useful configuration to add is PowerShell: Launch Script. With this configuration, you can specify a file containing optional arguments that are used whenever you press F5 no matter which file is active in the editor.
After the debug configuration is established, you can select which configuration you want to use during a debug session. Select a configuration from the debug configuration drop-down in the Debug view’s toolbar.
Troubleshooting the PowerShell extension
If you experience any issues using VS Code for PowerShell script development, see the troubleshooting guide on GitHub.
Useful resources
There are a few videos and blog posts that may be helpful to get you started using the PowerShell extension for VS Code:
Videos
Blog posts
PowerShell extension project source code
The PowerShell extension’s source code can be found on GitHub.
If you’re interested in contributing, Pull Requests are greatly appreciated. Follow along with the developer documentation on GitHub to get started.
PowerShell in Visual Studio Code
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 well as all versions of PowerShell Core.
Install the PowerShell extension
The official PowerShell extension can be installed by following the steps described in the Visual Studio Code User Guide or by going directly to the Visual Studio Code Marketplace and clicking the Install Button.
You can also install the PowerShell extension from within Visual Studio Code by opening the Extensions view with keyboard shortcut ⇧⌘X (Windows, Linux Ctrl+Shift+X ) and typing «PowerShell» and select the PowerShell extension:
Install from the command line
Alternatively, the PowerShell extension can be installed from any command line (including PowerShell, Cmd, bash) on all platforms using the following command
If you are running VS Code Insiders, you will need this command instead:
Example scripts
Example scripts are included with the extension and can be found at the following path.
To open or view the examples in Visual Studio Code, run the following from your PowerShell command prompt:
If using the Insiders edition:
You can also open the examples from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) with the PowerShell: Open Examples Folder command.
Major features
Debugging
The PowerShell extension uses the built-in debugging interface of VS Code to allow for debugging of PowerShell scripts and modules. You can learn more about VS Code debugging here.
Hey, Scripting Guy! blog
For more information on debugging, check out the «Hey, Scripting Guy!» two-part blog post series written by @keithHill on debugging with the PowerShell extension:
PowerShell extension settings
You can customize VS Code settings from the File > Preferences > Settings menu item (Code > Preferences > Settings on macOS).
You can also click the gear icon located in the lower left corner of the Activity Bar.
You can also use the keyboard shortcut ⌘, (Windows, Linux Ctrl+, ) to open your settings. The VS Code team has introduced a settings GUI in version 1.27.1 as the new default interface for customizing settings. In VS Code versions prior to 1.27.1, this will open your settings.json file.
You can still open the settings.json file by using Preferences: Open Settings (JSON) command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by changing the default settings editor with the «workbench.settings.editor» setting.
Go to User and Workspace settings for more information on configuring VS Code settings.
Multi-version support
You can configure the PowerShell extension to use any version of PowerShell installed on your machine by following these instructions.
You can also change the version by clicking on the version number in the lower right corner:
Or run the PowerShell: Show Session Menu command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
Pester
Pester is a Behavior-driven Development (BDD) based unit test runner for PowerShell. Pester provides a framework for running unit tests to execute and validate PowerShell commands. Pester follows a file naming convention for naming tests to be discovered by Pester at test time and a simple set of functions that expose a testing domain-specific language (DSL) for isolating, running, evaluating and reporting the results of PowerShell commands.
Windows 10 and Server 2016 comes with Pester 3.40 pre-installed. To update Pester or to install the latest version on other platforms follow the Pester installation instructions.
Plaster
Plaster is a template-based file and project generator written in PowerShell. Its purpose is to streamline the creation of PowerShell module projects, Pester tests, DSC configurations and more. See the GitHub Plaster repository for more information, for documentation on Plaster’s cmdlets see Cmdlet Documentation.
The PowerShell extension allows the creation of new Plaster projects by running the PowerShell: Create New Project from Plaster Template command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
PSScriptAnalyzer
PSScriptAnalyzer is a static source code checker for PowerShell modules and scripts. PSScriptAnalyzer checks the quality of PowerShell code by running a set of rules. The rules are based on PowerShell best practices identified by the PowerShell Team and the community. PSScriptAnalyzer generates diagnostic records (errors and warnings) to inform users about potential code defects and suggests possible solutions for improvements.
The PowerShell extension includes PSScriptAnalyzer by default, and automatically performs analysis on PowerShell script files being edited in VS Code.
PSScriptAnalyzer Settings
PSScriptAnalyzer is shipped with a collection of built-in rules that checks various aspects of PowerShell source code such as presence of uninitialized variables, usage of PSCredential Type, usage of Invoke-Expression, etc. Additional functionality such as exclude/include specific rules is also supported.
To disable PSScriptAnalyzer, open your settings, browse Extensions, select the PowerShell extension and deselect the checkbox for PSScriptAnalyzer.
Format document command is provided by the PSScriptAnalyzer module.
Document Formatting
CodeLens
CodeLenses are a VS Code feature to provide actionable, contextual information that is displayed within the source code.
CodeLens support was added in version 1.3.0 of the PowerShell extension, read the PowerShell extension changelog for more information.
Pester CodeLens support
Pester supports CodeLens integration for Run tests and Debug tests.
CodeLens Pester debug support
CodeLens Pester symbol support
Function reference CodeLens support
CodeLens function reference support shows the number of times a function is referenced within your code and allows you to jump to specific references.
Extension FAQ page
Check out the FAQ page on the PowerShell extensions Wiki
Types.ps1xml and Format.ps1xml files
ps1xml files are PowerShell’s way to extend the type system and define output formatting. For more information on these files, please refer to the official PowerShell documentation on Types.ps1xml and Format.ps1xml. You can get IntelliSense features when authoring ps1xml files by installing the XML extension by Red Hat. After installing, add this configuration to your user settings:
PowerShell
Microsoft
PowerShell Language Support for Visual Studio Code
This extension provides rich PowerShell language support for Visual Studio Code (VS Code). Now you can write and debug PowerShell scripts using the excellent IDE-like interface that Visual Studio Code provides.
This extension is powered by the PowerShell language server, PowerShell Editor Services. This leverages the Language Server Protocol where PowerShellEditorServices is the server and vscode-powershell is the client.
Also included in this extension is the PowerShell ISE theme for Visual Studio Code. It is not activated by default, but after installing this extension either click «Set Color Theme» or use the theme picker and select «PowerShell ISE» for a fun and familiar experience.
Platform Support
The extension should work anywhere VS Code itself and PowerShell Core 7 or higher is supported. For Windows PowerShell, only version 5.1 is supported. Please note that PowerShell Core 6 is end-of-life and so not supported. Our test matrix includes the following:
Read the installation instructions to get more details on how to use the extension on these platforms.
Read the troubleshooting guide for answers to common questions.
Features
Installing the Extension
You can install the official release of the PowerShell extension by following the steps in the Visual Studio Code documentation. In the Extensions pane, search for «PowerShell» extension and install it there. You will get notified automatically about any future extension updates!
You can also install a VSIX package from our Releases page by following the Install from a VSIX instructions. The easiest way is through the command line:
Script-based Installation
If you’re on Windows 7 or greater with the PowerShellGet module installed, you can easily install both Visual Studio Code and the PowerShell extension by running the following command:
You will need to accept the prompts that appear if this is your first time running the Install-Script command.
Reporting Problems
If you experience any problems with the PowerShell Extension, see the troubleshooting docs for information on diagnosing and reporting issues.
Security Note
For any security issues, please see here.
Example Scripts
There are some example scripts in the extension’s examples folder that you can use to discover PowerShell editing and debugging functionality. Please check out the included README.md file to learn more about how to use them.
This folder can be found at the following path:
To open/view the extension’s examples in Visual Studio Code, run the following from your PowerShell session:
Contributing to the Code
Check out the development documentation for more details on how to contribute to this extension!
Maintainers
Emeriti
License
This extension is licensed under the MIT License. Please see the third-party notices file for details on the third-party binaries that we include with releases of this project.
Debugging PowerShell script in Visual Studio Code – Part 1
Summary: Here’s a look at the many features of the PowerShell debugger for Visual Studio Code.
In previous blog posts, we covered how to get started with PowerShell development in Visual Studio Code and the editing features of Visual Studio Code and the PowerShell extension. If you don’t already have Visual Studio Code configured with the PowerShell extension, read those blog posts to get caught up.
In the first of this two-part series, we will cover the many features of the PowerShell debugger for Visual Studio Code. These features are provided by the PowerShell extension, or, more accurately, by the PowerShell Editor Services module which comes with the PowerShell extension.
PowerShell Editor Services runs in a separate process and supplies both language and debugging services to Visual Studio Code via a JSON remote procedure call (RPC) protocol that’s defined by Visual Studio Code. One advantage of this approach is that a crash of the PowerShell Editor Services process doesn’t cause Visual Studio Code to crash. And, with the latest version of the PowerShell extension, you can simply restart the current PowerShell session without restarting Visual Studio Code to get going again.
First look at the PowerShell Debugger in Visual Studio Code
Press Ctrl+Shift+P (Cmd+Shift+P on Mac) to open the PowerShell extension’s Examples folder, type PowerShell open examples, and then press Enter. After the Examples folder has loaded, open the DebugTest.ps1 file, and set a breakpoint on the line that has the Start-Sleep command. To set the breakpoint, either click in the left editor margin or press F9 to toggle the breakpoint on and off for the current line.
To open the Debug view, in the View Bar select Debug from the View menu or press Ctrl + Shift + D. In the Launch Configuration dropdown (shown in the following screenshot), select the PowerShell Launch (current file) configuration. Like the PowerShell integrated scripting environment (ISE), this configuration will execute the file that’s in the active editor window under the debugger when debugging is started.
Let’s start a debug session. First, make sure the DebugTest.ps1 file’s editor window is still the active window, and then press F5 or click the green Start Debugging button to the left of the Launch Configuration dropdown (shown in the previous screenshot).
After the debugger starts, you will see the Debug actions pane (shown in the following screenshot), and the debugger should pause at the breakpoint that you set.
The Debug actions pane provides buttons for:
Now, let’s look at the Debug view features that are available during a debug session.
The VARIABLES section of the Debug view allows easy inspection of variable values. The Auto group weeds out the PowerShell automatic variables and leaves just the variables you’ve defined and are likely interested in seeing. However, if the variable you are looking for isn’t listed in Auto, you can look for it in the Local, Script, or Global groups.
The WATCH section allows you to specify a variable or expression whose value should always be displayed.
The CALL STACK section displays the call stack, and you can also select a different frame in the call stack to examine calling functions, scripts, and the variables that are defined in those scopes.
The BREAKPOINTS section provides a central UI to manage, that is, create, disable, enable, and delete breakpoints that you may have defined over many different script files.
You can also see from the previous screenshot that you get hover tips when you hold the cursor over a variable. Hover tips can show simple values, like numbers and strings, or complex objects as shown in the following screenshot:
VARIABLES section
The VARIABLES section allows you to inspect variable values, including complex variables such as those shown in the following screenshot:
For primitive variable types, the value is displayed directly, typically as numbers, strings, and Booleans. For non-primitive variables, the type information is displayed. If the type is a collection or an array, the number of elements is displayed as well.
You can do more than just inspect variable values. To change those values, double-click the value that you want to change, enter a new value, and click outside the edit box to complete the operation.
Watch section
The WATCH section allows you to add a watch for any variable or expression. Simply click the + button (highlighted in the following screenshot), and type the variable name or a PowerShell expression:
This values will always be evaluated, if possible. Keep in mind that the variables entered as a watch may not be available in all scopes.
BREAKPOINTS
Besides setting line breakpoints, the PowerShell debugger allows you to set function breakpoints, conditional breakpoints, and tracepoints.
Function breakpoints
Remove the line breakpoint that we set earlier on the line that executes the Start-Sleep command.
Press F5 to start debugging the DebugTest.ps1 script, and you will see the debugger stop everywhere Write-Output is called. You can tell when the debugger is stopped on a function breakpoint by looking at the CALL STACK section of the Debug view. It will indicate that it is paused on a function breakpoint. The Debug Console will also indicate that a breakpoint has paused the debugger as shown in the following screenshot. If the Debug Console is not visible, select Debug Console from the View menu, or press Ctrl + Shift + Y.
Stop debugging (press Shift + F5), and remove the function breakpoint by right-clicking it in the BREAKPONTS section, and selecting Remove breakpoint.
Conditional breakpoints
After you set the breakpoint, you will see that conditional breakpoints are displayed with an “=” sign in the glyph:
Tracepoints
Let’s convert our previous conditional breakpoint to a tracepoint. Right-click the conditional breakpoint in the left editor margin, select Edit Breakpoint…, and modify the condition to:
Press F5 to start debugging. You will notice that the script runs to completion without ever breaking into the debugger. In the Debug Console (Ctrl + Shift + Y), you will see the following output from this tracepoint:
Hit count for breakpoints
Line breakpoints support not only condition expressions but hit counts as well. When you specify a hit count, the PowerShell debugger notes the number of times that the breakpoint has been encountered and only breaks into the debugger after the specified hit count has been reached.
Let’s set a line breakpoint with a hit count. First, remove all previous breakpoints in DebugTest.ps1 by using the Remove All Breakpoints button as highlighted in the following screenshot:
This UI allows you to set both Expression and Hit Count to have a conditional breakpoint that obeys the specified hit count. Let’s set the hit count to 25. Press Enter to complete setting the hit count.
In this blog post, we looked at the debugging features of Visual Studio Code and the PowerShell extension. All debugging examples in this post used a project that had the debugger “preconfigured”. In Part 2 of this series, we will look at how to configure the debugger to launch and debug your scripts.
I think you’ll find the PowerShell debugging experience in Visual Studio Code to be quite productive. Of course, if you do find a bug, please be sure to submit an issue at https://github.com/PowerShell/vscode-powershell/issues so that we can continue to improve the debug experience for everyone.
Keith Hill Software Engineer PowerShell MVP