Инструменты power shell для визуальной студии

It’s hard to leave behind a trusted tool in IT, but there are times when moving ahead requires letting go.

Out of the box, Visual Studio Code is a general-purpose code editor. It doesn’t flex its strengths until you install extensions for your language of choice. In this article, we’ll walk through how to install and configure the official PowerShell extension, cover the features it adds, how to debug PowerShell code and perform some basic Git interaction. By the end, you’ll be equipped to fully depend on VS Code for your PowerShell development needs.

How to add the PowerShell extension to Visual Studio Code

First, if you don’t have VS Code installed, you can download it for your operating system here. While all the examples in this article were run on Windows, the experience is cross-platform and applies to both Linux and MacOS running PowerShell 7. After installation, open it and select your theme of choice.

Next, click on the Extensions option in the sidebar and then search for PowerShell. Click on the Install button for the PowerShell extension from Microsoft.

Screenshot of search results for PowerShell extension.
Search for the PowerShell extension in VS Code then install it.

The first thing you’ll be presented with is a walkthrough. If you appreciate guided introductions, it is recommended to try it to get familiar with the recent updates.

At the bottom you should notice a new terminal window called PowerShell Extension and the command explorer should show on the sidebar. That will be a familiar sight if you are coming from Windows PowerShell ISE.

If you go to File > Settings and then expand Extensions > PowerShell, you’ll find the settings for the PowerShell extension. For example, if you use the Format on Save setting (Text Editor > Formatting), there are several options for how the system automatically formats your code. My favorite is to enable Code Formatting: Auto Correct Aliases for VS Code to replace aliases whenever you hit save.

https://youtube.com/watch?v=apasCOHOdhE%3Fautoplay%3D0%26modestbranding%3D1%26rel%3D0%26widget_referrer%3Dhttps%3A

How to use the PowerShell extension in VS Code

In VS Code, if you open a .ps1 file, VS Code automatically sets the language to PowerShell. If you open a new, unsaved file you have the option to select a language.

Clicking on Select a Language will open the command palette for you to select PowerShell.

foreach ($proc in (gps)){if($proc -ne $null){$proc.Name}}
Screenshot showing the problems tab in PowerShell extension.
The Problems tab points out errors in code.

This is how VS Code uses the PSScriptAnalyzer code analysis tool to help you write better code. For example, the if expression $proc -ne $null should be $null -ne $proc.

The IntelliSense feature in VS Code is an AI feature that offers coding suggestions. For example, if you remove line three and start typing $pr, then IntelliSense will provide a dropdown menu of possible autocompletes.

Screenshot of IntelliSense autocomplete feature.
The IntelliSense feature gives options to autocomplete the code.

And then, once you select $proc, you can add a period and see the available properties.

Screenshot of the assist feature in PowerShell code properties.
The autocomplete feature in VS Code also tries to assist with filling out the properties in your code.

IntelliSense also works with cmdlets. If you start to type a cmdlet name, then you’ll see a similar dropdown with several options.

Screenshot showing PowerShell cmdlet autocomplete feature.
The autocomplete feature also works with PowerShell cmdlets to speed up coding efforts.

When you get further along in your coding experience with VS Code, you can tap into the IntelliCode feature, which is another AI-based enhancement that offers suggestions based on the code you’ve written to speed up the scripting process.

How to debug PowerShell in VS Code

Debugging in VS Code is similar to the process in other integrated development environments. If we want to run a script and pause it on certain lines, select the line and press F9 or click just to the left of the line number.

Screenshot of VS Code breakpoint.
Set up a breakpoint in VS Code to pause the script at a certain point.

If you press F5 or go to the Run menu and select Start Debugging, the script will run until it hits the breakpoint and then it will pause and you can examine the variables.

Screenshot of VS Code debugging breakpoint.
VS Code stops at the breakpoint during the debugging process to let you look at the script variables.

In this case, I want to examine the $proc variable, so I’ll expand Script and scroll down. You’ll see that the first process running on my computer is 1Password.

Screenshot of PowerShell variable contents showing details of one variable.
Examine the variable contents while debugging the script.

I can step the script, meaning move it to the next breakpoint, by either pressing F5 or the step icon. In this case it will continue to break inside the foreach loop until it runs out of items being returned by Get-Process.

If you prefer to check the variables at a terminal, you can do so by typing in the variable name in the integrated terminal.

Screenshot of the VS Code terminal window.
VS Code provides the option to open the terminal to examine PowerShell code.

In this case, I’ve stepped through the code several additional times.

You also have access to other PowerShell debugger commands. You can continue stepping with the c command. For the full list of debugger commands, have a look at official documentation at this link.

When finished debugging, you can stop by pressing the Stop button or Shift-F5.

How to integrate VS Code with Git

Once you have a script written, debugged and ready to save, then you’ll want to commit it to Git, which VS Code integrates with natively. First, install Git at this link, then close and reopen VS Code.

:/>  Как закрыть фотошоп принудительно

With a new instance of VS Code open, use the Open Folder option to open an existing cloned Git repository or you can use the git command to initialize one with the git init command.

Once in that repository directory, I’ll go ahead and add a file, update it with my script contents, and then save it. You should see a 1 icon over the source control icon on the sidebar.

Screenshot of Git repository for PowerShell.
Use a Git repository to maintain PowerShell scripts with source control.

If you click on that icon, it opens the Source Control view where you can enter in a commit message about your change and commit your code.

Screenshot of Git commit message.
The VS Code source control view lets you enter a commit message on the script.
git config user.name "Anthony Howell"
git config user.email "[email protected]"

If you have a cloned git repository from a service such as GitHub or a remote server, then you have the option to Sync or Publish Branch if it’s a new branch.

Why it’s time to try VS Code for PowerShell scripting

Microsoft has invested a lot of effort to make PowerShell in VS Code a first-class citizen and has a team dedicated to maintaining the PowerShell extension. If you encounter an issue or find a bug with the extension, you can open a GitHub issue in the official repository. Fortunately, the extension is solid so your coding experience should go smoothly.

If you still use Windows PowerShell ISE, you should try VS Code for your PowerShell scripts. Another advantage of learning PowerShell in VS Code is it allows you to easily pivot into writing Terraform or even Python in VS Code so you can expand your skills in other areas.

Anthony Howell is an IT expert who is well-versed in multiple infrastructure and automation technologies, including PowerShell, DevOps, cloud computing, and the Windows and Linux operating systems.

You can use PowerShell ISE or Visual Studio Code to run a PowerShell script.

To run a PowerShell script using VS code, you need to first install the PowerShell extension in Visual Studio Code.

You can do this by opening the Extensions view using the keyboard shortcut Ctrl+Shift+X, typing “PowerShell” in the search box, and then clicking the Install button next to the PowerShell extension.

Once the extension is installed, you can easily write and run PowerShell scripts.

Open a new file, save it with a .ps1 extension, and start writing your script.

To execute your script, select the code you want to run, press Ctrl+Shift+P, and type “run selected” to find the Terminal: Run Selected Text In Active Terminal command.

Overview of Visual Studio Code

Visual Studio Code (VSCode) is a popular code editor developed by Microsoft. It is known for its lightweight design and robust functionality, making it suitable for various programming tasks.

For instance, enabling the files.trimTrailingWhitespace setting automatically removes excess whitespace from the file, keeping the code clean.

The integrated terminal is another standout feature. It allows developers to run commands directly within VSCode.

This terminal can be accessed by pressing `Ctrl+“ or navigating the menu.

VSCode offers a command palette, brought up by pressing Ctrl+Shift+P, which provides access to numerous functionalities, including running selected text in the terminal.

Files and projects are organized in a sidebar, making navigation straightforward.

The editor supports various programming languages, syntax highlighting, and debugging capabilities.

The console feature allows for debugging output, making tracking and resolving issues during development easier.

Run PowerShell Script in Visual Studio Code

To run PowerShell scripts in Visual Studio Code, you first need to install Visual Studio Code on your system.

Downloading Visual Studio Code

  1. Visit the Visual Studio Code website:
    • For Windows, Linux, and macOS, there are specific download links.

Install on Windows

  1. Download the installer: Make sure to download the setup for your version of Windows.
  2. Run the installer: Follow the on-screen instructions to complete the installation.
  3. Launch Visual Studio Code: After installation, open Visual Studio Code from the Start menu or desktop shortcut.

Install on macOS

  1. Download the .dmg file from the Visual Studio Code website.
  2. Open the downloaded file: Drag the Visual Studio Code icon to the Applications folder.
  3. Open Visual Studio Code: Launch it from the Applications folder or by using Spotlight Search.

Install on Linux

  • Debian-based distributions:
    1. Download the .deb package.
    2. Open a terminal and run: sudo apt install ./<file>.deb
  • Red Hat-based distributions:
    1. Download the .rpm package.
    2. Open a terminal and run: sudo rpm -i <file>.rpm

Installing PowerShell

After installing Visual Studio Code, install PowerShell to run scripts. PowerShell 7.2 supports Windows, Linux, and macOS:

  1. Install PowerShell Core:
    • Download packages from the PowerShell GitHub releases page.
    • Follow platform-specific instructions to complete installation.
  2. Verify installation: Open a terminal or command prompt and run: pwsh This command should start PowerShell if installed correctly.
:/>  Как повернуть видео на 90-180 градусов в плеере

Read PowerShell Data Types

Configure Visual Studio Code for PowerShell

Setting up Visual Studio Code for PowerShell involves installing the PowerShell extension and configuring the integrated environment. This setup provides features like IntelliSense, debugging, syntax highlighting, and a built-in console.

Utilizing the PowerShell Extension

To start, install the PowerShell extension from the Visual Studio Code Marketplace.

Open Visual Studio Code, click on the Extensions icon on the left sidebar or use the shortcut Ctrl+Shift+X. In the search box, type “PowerShell” and click the install button next to the extension.

This extension offers rich language support, such as IntelliSense for code completion, syntax highlighting for better readability, and debugging capabilities.

It also integrates with PowerShell Editor Services, enhancing the editing experience.

Once installed, restart Visual Studio Code to load the extension and its functionalities fully.

Set Up the Integrated Environment

After installing the PowerShell extension, configure the integrated console.

Navigate to File > Preferences > Settings. In the search box, type “terminal integrated shell” and update the terminal settings to set the default shell to PowerShell.

Next, open the keybindings.json file through File > Preferences > Keyboard Shortcuts and select keybindings.json to customize shortcuts for efficient workflow.

Add configurations for launching the PowerShell terminal directly within VS Code.

Configure language mode for PowerShell scripts to ensure proper linting and syntax checking.

Open a PowerShell script file, and an option to set the language mode appears in the bottom right of the screen. Select “PowerShell.”

How to Debug PowerShell Script using VS Code

Debugging PowerShell scripts in Visual Studio Code is straightforward. Begin by installing the PowerShell extension.

Open the Extensions view with Ctrl+Shift+X and search for “PowerShell”. Click Install next to the PowerShell extension.

To start debugging, open your PowerShell script. Set a breakpoint by clicking in the margin next to the line where you want the script to pause.

Breakpoints can be managed in various ways:

  • Line Breakpoints: Click the margin to add a breakpoint on any line.
  • Conditional Breakpoints: Right-click the breakpoint and add conditions like specific variable values.

Press F5 to launch the debugger. The script will run up to the breakpoint and pause.

Use the Debug View to inspect variables, call stacks, and watch expressions.

You can add variables to the watch list to track their values during the execution.

The Debug Console allows running commands interactively while paused.

Use commands like Get-Variable to inspect and modify variables.

Use CodeLens to see references and function details directly above the code. This helps navigate large scripts efficiently.

For script analysis, install PSScriptAnalyzer. This tool provides linting and script analysis to catch potential issues.

How to Work with Command Palette and Keyboard Shortcuts

Using the Command Palette and keyboard shortcuts makes working with PowerShell scripts in Visual Studio Code efficient and straightforward.

For example, to enable PowerShell ISE Mode, type “ISE Mode” in the palette and select PowerShell: Enable ISE Mode.

How to Run PowerShell Script in Visual Studio Code

Common Commands in the Command Palette

  • Open a new terminal: Terminal: Create New Integrated Terminal
  • Run a selected script: PowerShell: Run Selection
  • Format document: PowerShell: Format Document

Useful Keyboard Shortcuts

  • Open Extensions View: Ctrl+Shift+X
  • Run Code: F5
  • Stop Running Code: Shift+F5
  • Toggle Terminal: Ctrl+`

Editing and Navigation Shortcuts

  • Copy Line Down: Alt+Shift+Down
  • Move Line Up: Alt+Up
  • Go to Definition: F12
  • Find in Files: Ctrl+Shift+F

Read How to Run PowerShell Script From Command Line With Parameters?

Customize User and Workspace Settings

To access the Settings editor, navigate to File > Preferences > Settings.

Alternatively, press Ctrl+, on Windows and Linux or Cmd+, on macOS. This brings up a comprehensive interface for managing all configurations.

For quick changes, using the Command Palette is an efficient method.

Open it by pressing Ctrl+Shift+P, and type “Preferences: Open Settings”. This method allows you to modify settings without leaving your code window.

Example Settings to Configure

  1. Font Size:
    • Increase readability by adjusting font size.
    • "editor.fontSize": 14
  2. Theme:
    • Customize the look and feel by choosing from various themes.
    • "workbench.colorTheme": "Visual Studio Dark"
  3. PowerShell Extension:
    • Ensure PowerShell scripts have syntax highlighting and other features.
    • "powershell.codeFormatting.preset": "Custom"

Configuring the Status Bar

The Status Bar at the bottom can be customized to display important information. For example, you can show the currently active PowerShell version.

"powershell.integratedConsole.showOnStartup": true

Workspace Settings

Setting up workspaces allows project-specific configurations:

  1. Open or create a .code-workspace file.
  2. Define settings that apply only to the current workspace.
{ "folders": [], "settings": { "powershell.codeFormatting.autoCorrectAliases": true }
}

Testing PowerShell Scripts using Visual Studio Code

Testing PowerShell scripts in Visual Studio Code is easy.

First, ensure you have the PowerShell extension installed. This extension supports both PowerShell Core and Windows PowerShell 5.1.

:/>  Как сделать ярлык объекта на Android, зачем он нужен и как его создать

To start, open your script file in Visual Studio Code.

For testing purposes, use a command like:

Write-Output "Hello, World!"

To debug, add breakpoints by clicking on the left margin next to the line number.

Steps to Test:

  1. Press F5 to start debugging.
  2. The script runs and stops at breakpoints, letting you inspect variables.

PowerShell Integrated Console within the editor provides an interactive experience, allowing you to run and test scripts in real time. Press Ctrl+Shift+ to open this console.

Read PowerShell try catch examples

Handle Execution Policy Restrictions in VS Code

To run PowerShell scripts in Visual Studio Code, it’s important to handle execution policy restrictions correctly. Here’s what you need to know.

Execution Policy is a safety feature in PowerShell that controls the conditions under which PowerShell loads configuration files and runs scripts. Visual Studio Code respects these settings.

To view current execution policies:

Get-ExecutionPolicy -List
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force

To persist settings for different PowerShell versions or editions, use different commands and PowerShell executables as required.

Here’s a table summarizing common execution policies:

PolicyDescription
RestrictedNo scripts can run.
AllSignedOnly scripts signed by a trusted publisher can run.
RemoteSignedDownloaded scripts must be signed by a trusted publisher.
UnrestrictedAll scripts can run.

Frequently Asked Questions

How do I execute a PowerShell script using Visual Studio Code’s integrated terminal?

To execute a PowerShell script, open your script file in Visual Studio Code. Right-click inside the file and select “Run PowerShell Script.” Alternatively, use the default shortcut: F5. The script will run in the integrated terminal at the bottom of the window.

What steps are needed to run PowerShell scripts in Visual Studio Code on a Mac?

First, download and install Visual Studio Code for macOS. Open the app and go to the Extensions view (Cmd+Shift+X). Search for “PowerShell” and install the extension. After installation, you can open and run PowerShell scripts like Windows.

Where can I find and install the PowerShell extension for Visual Studio Code?

Open Visual Studio Code and go to the Extensions view by clicking the Extensions icon or using the shortcut Ctrl+Shift+X. In the search box, type “PowerShell”. The PowerShell extension should appear in the search results. Click the “Install” button next to the extension.

Can you run a PowerShell script in VS Code with PowerShell 7 integration?

Yes, you can run PowerShell 7 scripts in Visual Studio Code. Make sure you have PowerShell 7 installed on your machine. Open Visual Studio Code, and ensure that the PowerShell extension is installed. The extension supports PowerShell 7 and integrates seamlessly.

How to configure Visual Studio Code to run a PowerShell script as an administrator?

Conclusion

I hope you know how to use Visual Studio code to execute PowerShell scripts.

This can be done by opening the Extensions view and searching for “PowerShell.”

After installing the extension, syntax highlighting will start working automatically when a PowerShell script file is saved.

Typing “run selected” will allow execution of the highlighted code in the active terminal.

If you still have any questions, feel free to leave a comment below.

You may also like:

Requirements

  • Visual Studio 2017 (15.8+) or 2019

Info

PowerShell Tools for Visual Studio brings the richness of the Visual Studio development experience together with the power of PowerShell.  Using this extension, you can:

IntelliSense

PowerShell Tools provides IntelliSense for cmdlets, parameters, .NET classes, variables and paths.

Debugging

Set breakpoints and step through PowerShell scripts with the Visual Studio debugger. View local variables, call stack and set watch variables.

Project System

Organize scripts in a Visual Studio project that can generate manifests and package scripts as executables.

Interactive Console

The PowerShell Interactive Window provides an interactive console experience that supports IntelliSense.

Pester Test Adapter

The Pester Test adapter displays tests and allows you to run them from the Test Explorer window.

PowerShell Pro Tools provides additional features for PowerShell pros.

PowerShell 6 and 7 Support

Execute scripts in PowerShell 6 and 7 within Visual Studio.

Инструменты power shell для визуальной студии

Static Script Analysis

PSScriptAnalyzer support provides inline recommendations and quick fixes.

Инструменты power shell для визуальной студии

Windows Forms Designer

The PowerShell Windows Forms designer generates PowerShell script with the built-in, drag and drop forms designer.

Инструменты power shell для визуальной студии

WPF Designer

The WPF Designer generates event handlers and XAML loading methods automatically.

Инструменты power shell для визуальной студии

PowerShell Script Packaging

The PowerShell script packaging system compiles PowerShell scripts to executables with a large set of options.

Инструменты power shell для визуальной студии

Variables Tool Window

The variables tool window provides access to variables even when you aren’t in the debugger.

Инструменты power shell для визуальной студии

Modules Tool Window

The modules tool window displays modules loaded into the current session and available on the system.

Инструменты power shell для визуальной студии