Visual Studio Code as a PowerShell Integrated Scripting Environment
I know what you’re thinking. “Why use Visual Studio Code instead of the PowerShell ISE?” Well, if you’re using Mac OS or Linux, you don’t have the option to use the PowerShell ISE natively. And that’s a problem if you want to take advantage of the cross-platform capabilities of PowerShell Core. In this article, I’ll show you how to use Visual Studio Code (free!) to perform the key functions of the PowerShell ISE, namely:
- Simultaneously view code and execute it in the PoSh terminal
- Execute code on a selection or line-by-line basis (F8)
- Syntax highlighting (for people who are easily bored like me)
Installing Visual Studio Code
The best way to install most things is with a package manager. This would be something like apt-get or yum for Linux distros, homebrew for Mac OS, and Chocolatey for Windows. Or you could go old school and download it here.
Installing the PowerShell Extension
Go to the Extensions button (looks like a busted up square) or View > Extensions.
If the PowerShell extension doesn’t show up under the bombastic “RECOMMENDED” heading, just search for it in the “Search Extensions” field. Then install it.
Integrating the PowerShell Terminal
Open up a PowerShell script of your choice. Then in the menu, go to View > Integrated Terminal. You should see the following.
If you don’t see the PS
prompt Make sure you select “TERMINAL” and “PowerShell Integrated” from the drop-down menu.
Running Only Selected Code
In the PowerShell ISE, you can select a block of text and hit F8, and the ISE runs only that code. Or you can position your cursor at the end of a line and hit F8, and the ISE runs only the code on that line. Next we’ll enable the exact same behavior in Visual Studio Code.
Go To File > Preferences > Keyboard Shortcut
In the text entry field at the top, type “runsel”. You should see two items:
- “Run Selection” with a keybinding to F8
- “Run Selected Text In Active Terminal” with no keybinding
This is not what we want because it will not run the selected text in the PowerShell terminal. It will run the selection in the “OUTPUT” section, but not in the terminal. Obviously, that’s not the normal behavior of the PowerShell ISE. Let’s fix it.
Right-click the “Run Selection” item and select “Remove keybinding”
Right-click the “Run Selected Text in Active Terminal” item and select “Add Keybinding”
Depress the F8 key (or whatever you want to use) then hit Enter.
Testing It Out
Go back to your code and select a block of code. Hit F8 and watch the magic!
That’s what I’m talking about!
But… as of this writing, there’s an issue with this that’s being tracked on the vscode-powershell GitHub repo, and it’s this: multi-line input in the integrated console doesn’t work. That means you can’t select a function
block, hit F8, and have it work. It will throw ugly errors in your face.