PowerShell with Vim

05 Apr 2018
 

Using Vim with and to write PowerShell!

Not as good as VSCode

When it comes to writing large PowerShell scripts, VSCode is plain better, thanks to Microsoft’s extension for PowerShell (there are extensions to emulate Vi key bindings too). To be honest, the PowerShell ISE is also a better bet. But! There are some cases where it can make sense to use Vim, mostly when you want to quickly write a short script or make a small change to a pre-existing script. Vim launches faster than VSCode (not that VSCode is at all slow) and, provided you know the correct key bindings, can often be quicker to perform the edit with. Or maybe you just like using Vim!

Neovim

If you’re wanting to use Vim to write PowerShell, even with the introduction of cross-platform PowerShell core, chances are you’re on Windows. If that’s the case I recommend using Neovim with the Neovim-Qt GUI. Using a GUI just feels more natural on Windows and Neovim-Qt is cleaner out-of-the-box than gVim. I’ve also run into fewer problems running Neovim than I have with Vim when on Windows.

Windows clipboard

To get Ctrlc/v copy/paste working for Neovim-Qt when in insert mode just add source $VIMRUNTIME/mswin.vim to your vimrc file.

On Windows, Neovim’s vimrc file is located at %USERPROFILE%\AppData\Local\nvim\init.vim.

Setting Posh as Vim’s shell

By default, shell commands use cmd.exe, to use PowerShell instead just add the following snippet to your vimrc file.

set shell=powershell.exe
set shellcmdflag=-NoProfile\ -NoLogo\ -NonInteractive\ -Command
set shellpipe=|
set shellredir=>

Adding -NoProfile\ when setting shellcmdflag stops PowerShell from loading your profile every time you run a shell command from Vim, e.g. :!ls, but still loads it when creating a Neovim terminal buffer, :terminal.

ps1.vim

To add syntax highlighting, I use this plugin. It does what it says on the tin! I recommend using vim-plug for managing plugins if you’re not using something already.

Abbreviations

It’s good practice to use a cmdlet’s full name when writing PowerShell scripts so I like to set up abbreviations for my most frequently used aliases e.g.

:ab ls Get-ChildItem

Since abbreviations activate just the same when writing comments or strings (you might not want them to), I avoid setting them for cmdlet aliases that I rarely use.

Reuse

As I don’t want these abbreviations when using vim for anything but PowerShell I put them in ftplugin\ps1_ab.vim instead of my vimrc file. They are then only loaded when the filetype is ‘ps1’. Because I have ps1.vim installed (see above) the abbreviations will be picked up for other PowerShell file extensions too, e.g. .psm1.

For the sake of using vim-plug to manage ps1_ab.vim, I keep it in a Git repository and just add Plug 'robin1996/posh-ab' to my vimrc file.

My full vimrc file