PowerShell with VS Code

As a dev I've always thought of PowerShell as an IT Admin's tool and not really for me.

But recently I've been finding more and more use cases for PowerShell - including manipulating SharePoint Online which I'll cover separately.

So as a PowerShell noob, how do you get started?

First things first - if you haven't worked with it yet, PowerShell is probably locked down on your machine. This is for your own protection - but we need to open it up if we're to do anything useful!

From your Start Menu, type PowerShell and when the Windows PowerShell icon appears right-click it and choose: Run as administrator
(NB - don't choose Windows PowerShell ISE - that's a PowerShell editor. More about that later)

This will open a PowerShell window that looks a bit like the command prompt.

To allow you to run PowerShell scripts type: Set-ExecutionPolicy Unrestricted and hit enter.

Confirm that you want proceed by entering Y (for Yes) or A (Yes to all)

It's important to realise that your machine will now run ANY PowerShell script - so when you've finished working with PowerShell you should lock it down again with: Set-ExecutioPolicy Restricted

NB - Set-ExecutionPolicy includes options to run Unrestricted for the current user or for the current session.

OK - so how are we going to write some PowerShell? We could continue bashing commands into the window we opened, but let's open a proper editor that will allow us to script and debug.

The original editor, still included with Windows, is the PowerShell ISE. This is a reasonable choice, much used by IT Admins - but it's been superceded by the cool new kid that is Visual Studio Code.

VS Code is a lightweight, but very powerful, IDE. It integrates with Git for source control and via its vast ecosystem of extensions can be used for writing script and code in many many languages.

If you don't have VS Code go ahead and install it.

Next you'll want to install the PowerShell extension. This can be done from the Extensions icon on the left-hand side, or by following the pop-up prompts if you open a ps1 file.

If you have used PowerShell ISE before you can tell VS Code to mimic the layout and colours of ISE.

With the PowerShell extension installed we can now start writing scripts - debugging them as we go, with the following commands:

F8 - execute the selected text
F5 - run and debug

While debugging you can set breakpoints, view variable values and set through the execution. It should be very familiar if you've debugged C# in Visual Studio before.

So, this was just a quick look at setting up VS Code for the first time to author PowerShell scripts. Next time we'll look at an example targetting SharePoint Online.

Happy coding!

Comments