Visual studio code and PowerShell
IntroductionVisual Studio Code (aka VSCode or just Code) has been around for a few years now. The 1.0 release came out in April of 2016 and from there we have seen feature after feature added with every release. VSCode is a free, cross-platform source code editor that offers you the ability to perform development operations like debugging or running task. It is has become more and more popular with each release and is picking up use in PowerShell development. I use VSCode now for building out PowerShell automation scripts or contributing to GitHub repositories that utilize the PowerShell language. In the content below I give you a walk-through of how to get VSCode setup. One repository I am a major contributor for is dbatools, and I use VSCode and the Git integration exclusively for this work. The PowerShell module, dbatools, is one that if you have to support one or more SQL Servers, you need to look into what this module offers. It has a wealth of commands to make any DBA's life easier. It is a SQL Server community-driven and supported module that is hosted on GitHub. Since VSCode is the primary editor I use I will go over how to use it to interact with the dbatools repository. Let's get started...
InstallVSCode is a cross-platform tool that works on Windows, Linux and Mac. You can download your specific OS flavor here. Just note that I only use Windows, so if you are on another OS your mileage may vary. If you favor being a beta tester you can download the Insiders Edition from the same page. The VSCode team made some visual cues to easily indicate what edition you are using, as they can be used side-by-side:
Where to StartGetting started with VSCode can be a bit challenging at first if you normally use something like the PowerShell ISE. Just like any new tool it requires a bit of time to acclimate yourself to it. The documentation for VSCode is laid out well and was a big help for me getting started. I would encourage you to spend time going through, at a minimum, the following sections:
- The Basics of Code (layout and how to move around)
- Code Extension Marketplace (how to expand what VSCode can do, will go over these in a bit)
- Version Control (Git integration)
- Integrated Terminal
Command PaletteI want to bring special attention to this because almost everything you can do via a menu or button in VSCode, can also be done via the command palette. The nice part of the palette is it will provide help along the way as you type. To open the command palette you can use the keyboard with CTRL+SHIFT+P or access it via the View menu. Any extension that has commands is going to show in the format of "extension name: command", so typing "powershell" will show any command that comes with the extension (once you install it). You can do the same thing for Git, just type that in and all the commands that are supported show up. There are additional commands outside of the extensions that are provided with VSCode, that I tend to use a good bit. I've included the most common below, along with the keyboard shortcut (if they have one):
- Trim Trailing Whitespace (CTRL+K, CTRL+X)
- Change Language Mode (CTRL+K, M)
- Format Document (SHIFT+ALT+F)
- Change All Occurrences (CTRL+F2)
Quick OpenCTRL+P provides a quick open prompt. This will list any recent file you have opened, but you can also use it to find a file within your current session of VSCode. So if you have a folder open with multiple files, just hit CTRL+P and start typing the file name. If a match is found it will be selected, you can just hit enter to open it. Another feature is if you open a PS1 file that may have multiple functions in it, hit CTRL+P and then type the at symbol ("@"):
ExtensionsThe single item below is the only extension you truly need to start developing PowerShell in VSCode:
Non-AdministratorThe installation for VSCode would require you to have Administrator privileges. If you find you need to work without Administrator rights to install extensions you can try the manual method. VSCode extensions are just VSIX files so you can download the file and manually add it in VSCode. You will find the latest VSIX file on the extension's release page on GitHub. You can get to that repository by searching GitHub or from the "Resources" section on the marketplace page. The file for the PowerShell extension will be named something similar to "PowerShell-x.x.x.vsix". Once you download the file just follow the steps below:
- Open the command palette.
- Type in "ext install from vsix" and hit enter
- Browse to the VSIX file you downloaded
- You will then receive a prompt to reload VSCode.
Code's SettingsIn VSCode you work with files or folders. Opening a folder is equivalent to a project in Visual Studio. One thing to understand is adjusting the settings in VSCode can apply to the "user settings" or "workspace settings". User Settings overwrite VSCode's default settings, and Workspace Settings can overwrite User Settings.
Workspace SettingsWorkspace settings apply to a folder you open with VSCode. When you open a folder and first open workspace settings, you will see a new folder is added, ".vscode". Any Extension or settings in VSCode you manipulate within your workspace settings will be saved under ".vscode.json". The following are settings recommended (as a baseline) for contributing with dbatools. Just paste them into the workspace settings. You can access it via the command palette, just start typing "Preferences", and you will see "Open workspace settings" in the list.
// Place your settings in this file to overwrite default and user settings.
// Windows 8.1 and below require you to specify PowerShell for the Integrated Terminal
// If you are also on another OS you will need to specify the path to PowerShell.exe
Clone dbatools repositoryWe first need to clone the repository before we can start contributing:
- Grab the "Clone with HTTPS" URL of your fork of dbatools.
- Open the command palette (CTRL + SHIFT + P)
- Type in "git clone" and press enter
- Paste the URL (CTRL + V) copied in step 1 into the prompt.
- Select the root folder where you want the repository to be kept (e.g C:).
Add an UpstreamVSCode includes Git integration, which means you can use the command palette or the Git sidebar to perform Git commands within the same program. There are, however, some that are not supported at this time. In those cases, you will need to revert to the command line or your tool of choice (e.g GitHub Desktop). If you favor the command line this is where the integrated terminal (CTRL+"backtick") allows you to stay in VSCode. When you fork dbatools to your GitHub account you will clone that repository, this is referred to as your "origin" remote. You just need to add another remote reference to the dbatools repository. This will make it a much smoother process to update your fork with the latest additions/modifications of dbatools.
Add upstream remoteThe following command creates a remote reference. You can name it whatever you want, but the standard term used with Git is "upstream".
git remote add upstream https://github.com/sqlcollaborative/dbatools.git
After you run that command you can verify it was created as below:
Pull down updatesOnce you have the remote that points to dbatools, you can use a few commands to pull down the changes. The following command updates all of the references to your remote repositories (origin and upstream).
git remote update
git pull upstream development
- Click on indicator in the status bar (the circle will start rotating)
- Open the command palette (CTRL+SHIFT+P), type "git sync" and hit enter.
- Open the Git sidebar, click on "..." at the top of the sidebar and click "sync".
Branching OutA branch is basically just a pointer to the current state of the current branch you have checked out. When you clone dbatools and open it in VSCode the first time should have the "development" branch checked out.
- Open the command palette
- Type "git branch" and hit enter
- Provide your desired branch name and hit enter
Commit OftenIt is often said "commit often" when you are using Git. It can help to make small changes, commit them, test them, and if something breaks roll-back that commit. VSCode offers you the basic ability of performing a commit but you can only roll back your last commit. So if you make a modification to a file, you will see an indicator on the Git sidebar. Once you open that sidebar you can add your commit message and commit your change, all within VSCode.
An Extra - Running PowerShell CodeIf you are coming from the PowerShell ISE you may have gotten used to clicking the buttons on the toolbar to run either the whole script, or just the current line (or selected). In VSCode there are a few shortcomings in this area because there are no buttons. There are however key bindings/mappings that can be used.
Extensions - KeymapsIf you work with Atom or Sublime you can search the marketplace for "keymaps" and find a few extensions offered that will give you similar keybindings...note there is also one for Visual Studio.
KeybindingsBy default the following keys are bound to the noted actions:
- F5 - Starts debugging the current file (has to be saved with the ps1 extension)
- F8 - Runs the currently focus (line or selected code).
// Place your key bindings in this file to overwrite the defaults
"when": "editorTextFocus && editorLangId == 'powershell'"
So here's a short example, open a new file add one or two PowerShell commands. You will need to open the Integrated Terminal, so a PowerShell session is running, and then just place the cursor on a line and hit F8.
An Extra-Extra - PSScriptAnalzyerThe PowerShell extension packages the PSScriptAnalyzer module which allows VSCode to check an open PS1 files against the PSSA rules. As the extension is released they bundle the latest version of the PSSA module. You can find what version is included by checking the following path on a Windows machine:
# "x.x.x" is current version of the extension you have installed
PSSA performs checks based on best coding practices and identifies the line of code that violates them. You can view these by using "CTRL+SHIFT+M" to open the "Problems" pane. You also have an indicator on the bottom left of the status bar of VSCode (clicking this will also open the "Problems" pane.