Paste JSON as a PowerShell Class in Visual Studio Code

The PowerShell extension for Visual Studio Code just got way cool.

First, we got a $profile. It lets you customize your environment and add session-specific elements to your PowerShell Visual Studio Code session.

Second, we got a way to interact from PowerShell directly with the vs code editor.

You use Register-EditorCommand to register a PowerShell function|scriptblock. In the PowerShell script you can set it up to a take a “context” parameter that gets passed in. This parameter contains a reference to the vs code editor (in the future this reference will surface more features), you can now do things like InsertText into the active file.

ConvertTo-Class

I took my existing PowerShell module and added this handful of code to connect it to Visual Studio. ConvertTo-Class takes a JSON string, figures out it structure plus data types and code generates a PowerShell v5.0 Class.

In Action

If you have PowerShell v5.0 installed, you can grab the ConvertTo-Class module from the command line like this Install-Module ConvertToClass

Edit your PowerShell VS Code $profile and add Import-Module ConvertToClass.

Start VS Code. In VS Code you can edit both a JSON file and PowerShell file and have a rich editing experience for each.

Here, I’m copying a JSON snippet of an Azure Resource Management (ARM) Template, then switching to a PowerShell file and pasting it as a PowerShell Class.

That’s the quick tour. PowerShell module authors just got some really cool integration tools for Microsoft’s new modern editor, Visual Studio Code.

I can’t wait to see what the community starts to add to the ecosystem.

Resources

Check out these links for more info.

PowerShell is a Query Language for JSON

PowerShell, as is, has all the tools you need to query JSON and then reshape, re-purpose it to what you need.

Result

Who Moved the Cheese – Microsoft’s new editor “Visual Studio Code”

Microsoft VS Code reached the 1.0 milestone and announced Version 1.0 of Visual Studio Code.

It is code editing redefined. Plus, PowerShell support for syntax highlighting ships in the box, and you need to install the extension (see VS Code Extensions to see how to) to get the rest, intellisense, debugger and much more.

I’ve been lucky to be involved with the PowerShell Editor Service, I’ve made contributions to it and have be around many great conversations about features now and to come.

Here is the Expand Alias feature I contributed.

VS Code

VS Code launched a year ago, there have been 2 million installs of VS Code. There are more than 500,000 people actively using VS Code each month.

  • Intelligent editing
  • Powerful debugging
  • Built-in Git support
  • Hundreds of extensions

What started as an experiment to build a production quality editor using modern web technologies has blossomed into a new kind of cross-platform development tool, one that focuses on […] productivity by centering the product on rich code editing and debugging experiences.

Really Cool

Besides the fact that I can a huge amount of work for PowerShell in VS Code, I found this next part really cool.

I’ve been doing more work in Azure and after I did a PaaS deployment of an App Service, I exported the configuration from the Azure Portal to a zip file.

The zip had five files, deploy.ps1, deploy.sh, DeploymentHelper.cs, parameters.json, and template.json. I extracted the files and then typed code . to launch vs code telling it use the current directory as my “project”.

Here’s where it gets cool, there are 4 different file types in that Azure export. A PowerShell file, Linux Shell file, a C# file and JSON files.

NOTE: I have these two Visual Studio Code extensions installed C# and Azure Resource Manager Tools.

From VS Code, I clicked on each file and VS Code provided me syntax highlighting, and intellisense for the PS1 and C# files and for the JSON files, because they are ARM templates, the Azure Tools extension gave me intellisense based on the ARM schemas defined.

Check it out

Editing four different file types, supporting syntax highlighting and more.

All in one place I could easily edit each file and in the case of the PowerShell script, I could run it from vs code, debug it and get all the intellisense I expect from other environment.

Fantastic!

VS Code Extensions

It is super easy to get these extensions in your environment too. After installing vs code, run it. For example, from a PowerShell prompt type code and press enter. After it launches, press F1. This will give you a dropdown at the top, it’s called the command palette, something you’ll use a lot. Next, type ext inst, press enter. This will query the Visual Studio Code Marketplace for published extensions.

When the list is returned, you can start typing the name of the extension you want, the list will update with matches. Type powersh. Next to the highlighted selection, you should see some blue boxes, you can click on the ReadME, License to read about these details or the Cloud and Arrow to download and install the extension. After it is installed, VS Code needs to restart and will prompt you if you want to do it now or defer to later.

Once installed and restarted the extension, when you edit a PowerShell file you’ll have even richer features at your fingertips. Repeat this to install the C# and Azure Manager Tools extension. Also, browse through the list to see what other extensions meet your needs.

VS Code Pandoc

This is a vs code extension that I wrote and published. I work a lot with markdown files. Visual Studio Code not only supports editing these files, it also has a live preview of them.

I ran across a free tool called Pandoc it renders markdown into amazing number of formats. The ones I’m interested in, PDF, Word Docs and HTML

NOTE: If you want to render to PDF you need to install MiKTeX for pandoc to generate it.

Install Follow the instruction in VS Code Extensions, search for pandoc and install.

In action

Here’s what the interaction looks like when rendering markdown to other formats in VS Code.

Check out vscode-pandoc in the market place.

More Productive

Visual Studio Code is a very impressive editor. For PowerShell, I’ve opted to do more of my PowerShell scripting in vs code. Yes, there are pieces missing, but not for long. Plus, if you are editing more than one type of file in your day, it’s worth checking out vs code. The sooner you do, the sooner you’ll find the moved cheese and be more productive.

NOTE: We haven’t even talked about how easy it is to create vs code extensions to fit your workflow.

Books about modern cloud products, companies and cultures

From this tweet to links and pictures.

Domain Driven Design

In Search of Certainty: The science of our information infrastructure

Release It!

Drift into Failure: From Hunting Broken Components to Understanding Complex Systems

Systems Thinking, Third Edition: Managing Chaos and Complexity: A Platform for Designing Business Architecture

The Principles of Product Development Flow: Second Generation Lean Product Development

Antifragile: Things That Gain from Disorder

Irresistible APIs: Designing web APIs that developers will love

Cloudonomics, + Website: The Business Value of Cloud Computing

Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation

Images from Microsoft Bing API with PowerShell Get-BingPics

PowerShell script for searching and downloading images from the Bing API. Inspired by this Python script Images from the iTunes/App/Mac App Stores.

Grab it

I put it up on on this GitHub repository.

Note: You need a Bing API Key to make it work.

You can pipe or pass a query to Get-BingPics:

Get-BingPics powershell or echo lions tigers bears liger | Get-BingPics

The script will look for your Bing API key in $env:BingPicKey, build the url with the query (line 17) and then use Invoke-RestMethod passing the api key in the header using basic authentication (line 19).

Lines 21-23 loops through each of the found images, creating an html anchor tag, with the image. Lines 25-32 create and html snippet and {1} (line 29) is replaced with anchor tags. This string is sent to a file and then in line 34, Invoke-Item launches it in your browser.

Tracking PowerShell Gallery Downloads

The PowerShell Gallery has a Version History at the bottom of each page for the modules that are published. It’s a good quick indicator showing the versions that have been pushed, the date it was updated and the total number of downloads.

If you’re a module owner and have more than one module on the gallery, there is no PowerShell cmdlet that lets you retrieve these stats. So, you need to click through multiple web pages to get information.

PowerShell Excel Module

I added two new features to my PowerShell Excel module, a new cmdlet Import-Htmland a new parameter PassThru on the Export-Excel cmdlet.

Import-Html

Lets you scrape a URL and specify an index of a table you want to return. It converts the data to PowerShell objects and then creates a spreadsheet for you.

Needs More Info

This is a great start, it be great if you could also see the total number of downloads for the module and the number of days that version was up on the gallery.

The Script

This script uses Get-HtmlTable (Invoke-Html wraps this) which is a tweaked version of Lee Holmes Extracting Tables from PowerShell’s Invoke-WebRequest. The property Days On Gallery is calculated and add to PowerShell objects return from the gallery html table.

In the End Block, the data is exported to Excel specifying the -PassThru parameter. The -PassThru parameter returns the newly created Excel SpreadSheet to the script so it can be customized. We customize it by added a new value and formula to cells E1 and E2. In cell E2 we add a built-in Excel function, Sum, telling Excel to sum the values of column C (this is our Downloads column from the Html Table on the gallery).

This example shows how you can let PowerShell and Excel do the heavy lifting for you and play to each of their strengths.

Grab the PowerShell Excel Module

If you’ve published one or more PowerShell modules to the gallery and want to get stats on your contributions, this’ll make life easier. Plus, you can tweak the script to customize it further.

Here on the Gallery or here on GitHub

Import-Html: Use PowerShell to Export HTML Tables To Excel

Added a new feature to my PowerShell Excel Module, Import-Html. Provide the URL of the page that has the table html tag and the index, starting at 0, identifying the table in the HTML to return.

It locates the table, grabs the headers if present (or creates them on the fly) and finally exports them directly to and Excel spreadsheet.

Get the Module

Grab the module from either the PowerShell Gallery or GitHub.

PowerShell Hashtables – You’re doing them wrong

Update from the PowerShell team:
$h.$key will perform very differently if $key has many unique values

$h.["abc"] or $h.abc will perform roughly the same in a loop.

Both versions add the numbers 1 to 1000 as keys to a hashtable.

The difference? The second version is 100 times faster.

In PowerShell you can access the key of a hashtable with dot notation, the first way or with indexer notation, the second way.

Slight difference in syntax, significant difference in performance.

Note: I found this out when building this Native PowerShell Spelling Corrector – Google Style.

Native PowerShell Spelling Corrector – Google Style

Peter Norvig, Director of Research at Google, posted “How to Write a Spelling Corrector”.

The PowerShell version reads a text file that has ~110K words, creates a lookup dictionary, and produces a list of possible corrections based on the edit distance between two words. See Mr. Norvig’s post for details.

All this in a page of PowerShell script, and it comes back in less than a second.

Invoke-SpellCorrector speling

Ported To PowerShell

I ported this back in 2007, PowerShell v1.0. Grab the script and the homles.txt file from GitHub.

Web Scraping with PowerShell – PDF Files

Often times you want the information that is in a PDF. You want to extract data, munge text for input to another process, or parse and save the results to a database.

Parsing PDF data is a challenge, fortunately there is a great library iTextSharp that does the job for you. You can download it from NuGet Gallery and it’s written for .NET. That means you can use in PowerShell to automate PDF processing.

Get-PDFContent

Here is a script that lets you read a PDF and extract the content as a string.

Dot source the script and you can start reading local PDF files.

Bonus Points

This same script let’s you read a PDF straight from the web.

Grab the PowerShell Script and iTextSharp

The PowerShell script and iTextSharp DLL are here on my GitHub repo.