PowerShell Script To Generate New Blog Post For Gatsby

What previously ran on Hugo is now running on GatsbyJS. For no other reason than that I’ve found myself increasingly using GatsbyJS for both work and personal projects, so it made sense to move this site to a platform I was using elsewhere.

To provide some background on the file structure I’m using so the script below makes more sense, in the Gatsby folder I have a content subfolder that contains blog posts. In there are three subfolders that are of relevance.

  1. blog: These are the completed posts that are published (you’re reading one right now!)
  2. drafts: In progress posts which are not yet published
  3. skeleton: A folder with a single file that contains a template markdown file to be used for future posts

Each post is a folder in either blog or drafts, with the folder name being the slug of the post. The post content is in a file named index.md in that folder, along with any images that go with the post. For example, the path to this blog would be content\blog\powershell-script-to-generate-new-blog-post-for-gatsby\index.md

The Skeleton

The index.md file in skeleton is just a template file I use to build new posts. This isn’t really necessary, it could all be done in the PowerShell script, but this is a bit cleaner.


title: __title__
uid: __uid__
date: __date__
tags: []

The PowerShell


$Title = Read-Host "Enter title"
$Date = Get-Date -Format "o"
$UID = (New-Guid).guid

$Slug = ($Title -replace "[^a-zA-Z\d\s:]","" -replace " ","-").ToLower()
$Title = (Get-Culture).TextInfo.ToTitleCase($Title)

New-Item -Type Directory -Path .\content\drafts\$Slug | Out-Null

$Index = Get-Content .\content\skeleton\index.md
$Index = $Index.Replace('__title__', $Title)
$Index = $Index.Replace('__date__', $Date)
$Index = $Index.Replace('__uid__', $UID)

$Index | Out-File .\content\drafts\$Slug\index.md -Encoding utf8

The Batch

Finally, as we can’t double click on Ps1 files to execute them, I’ve wrapped it in a clickable batch file.


powershell.exe -executionpolicy bypass -file z-new-post.ps1

If you enjoyed this post consider sharing it on , , , or , and .