I’ve been mucking about with Vim a bit recently and recently found myself (for reasons unknown tbh) writing powershell scripts in it.
Once I’d written a script, I would exit Vim to run it…however…that got me thinking, can I run powershell scripts directly in Vim?
DISCLAIMER – There’s no real reason to do this, I’d recommend using Visual Studio Code if you’re working with powershell. This is just a bit of fun
Anyway, there does seem to be a bunch of different ways to run code directly from Vim but I thought I’d share the way I’ve been doing it.
First things first, let’s install Vim. The easiest way to do so is via chocolately: –
choco install vim-tux
Once that’s installed we’re good to go! Let’s create a simple test file: –
New-Item C:temptest.ps1
And now open it in Vim: –
vim C:temptest.ps1
Let’s run something simple to try it out, add the following to test.ps1: –
$psversiontable.psversion
Ok, to run that line of powershell, hit esc and then type: –
:.w !powershell
And hit enter!
What this is doing is sending that one line to powershell which is then executing it. But what if we want to execute multiple lines of code?
To do that, we hit v to enter visual mode in Vim, then select the lines we want to execute with j, and then enter: –
: w !powershell
Vim will automatically add in ‘<,’> after the colon which indicates the selected lines.
So say we wanted to retrieve the versions of a bunch of SQL instances with this: –
Import-Module sqlserver $Servers = Get-Content C:tempsqlserver.txt foreach($Server in $Servers){ Invoke-SqlCmd -ServerInstance $Server -Query "SELECT @@VERSION" }
We can do that (somewhat) easily!
Kinda cool, eh?
Oh, and if you want to get rid of that annoying logo that pops up when powershell starts…add this to your vimrc file: –
cnoreabbrev powershell powershell -nologo
N.B. – The vimrc file usually lives at C:usersUSERNAMEvimfilesvimrc, you may need to create the folder and the file itself.
Ok, not the most practical way of running powershell code but I thought it was kinda cool
Thanks for reading!