How to set up Google CLI command aliases in Windows PowerShell

Saving common commands can save a lot of time and headache

Alexander Weston, PhD
Towards Data Science

--

The Fox and the Lion. Wenceslas Hollard. Wikimedia Commons.

Background

Google‘s Cloud Software-Developer Kit (Cloud SDK) is an essential tool for managing your Cloud projects locally. In Linux or Mac, SDK command are automatically inherited by the terminal making it easy to set up command aliases in your .bashrc and elsewhere

Unfortunately, in Windows, SDK installs as a separate application that doesn’t seem to inherit your terminal profile.

It’s a few steps to set up your Cloud profile (and requires that you use PowerShell) but this is best way I could figure out to do it. And it saves time in the long run not having to copy and/or re-type commands.

Setup

If you’re on an institutional laptop, you’ll need to have administrator rights enabled.

Firstly, launch PowerShell in the Start Menu.

PowerShell installs a slightly different set of tools through Google Command-Line Interface (Google CLI), not SDK. Run the following command in PowerShell (instructions).

Install-Module -Name GoogleCloud -Repository PSGallery -Force -AllowClobber

To save commands that persist between sessions, you’ll need to set up a PowerShell profile. This profile is loaded when you launch a new PowerShell session (similar to .bashrc).

Here’s a full article for creating a PowerShell profile. Simple instructions below.

Run the following in PowerShell to create a new blank profile:

New-Item -path $profile -type file -force

This will create a new file in your Documents folder, for me in
C:\Users\*\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

PowerShell output describing where the profile script is saved. Image by Author.

Open up “Microsoft.PowerShell_profile.ps1” in Notepad. This is where you can add your Google CLI commands (or any other commands, for that matter).

In PowerShell, multi-word commands save as “Functions”. The syntax for a function is —

Function alias {commands to run}

For example, you may want to save the command for ssh’ing into your DLVM with port forwarding (note that syntax is a bit different in Windows).

Function gssh {gcloud compute ssh my-dlvm --project my-project --zone my-zone '--' -L 8787:127.0.0.1:8787

Here’s a snapshot of a few of my commands

My PowerShell profile saving a few common Google CLI commands. Image by Author.

Much easier!

Running command aliases in PowerShell. This is what it looks like when it’s working. Image by author.

If you’ve come up with a better way to do this, please let me know in the comments…

~AW

--

--