PnP PowerShell and more...

Here I occasionally post about Microsoft 365 Patterns and Practices in general and PnP PowerShell more specifically.

PowerShell: Easy Navigation Between Folders

2020-10-13 2 min read PowerShell

PowerShell Tab Completion Animated Gif

If you, like me, have a folder where you navigate to a lot in PowerShell maybe this tip is a handy one for you. The folder in my case contains my GitHub/Code repositories.

I navigate around on my computer with PowerShell, but sometimes I simply want to jump back to that location from wherever I am, without needing to enter something like cd c:\users\erwin\repositories\myrepositoryfolder etc. etc.

Wouldn’t it be nicer if you get enter something alike repo myrepositoryfolder instead? Let’s set that up:

Step 1: Make sure you have a PowerShell Profile file in place.

If you don’t, it’s very simple to create it. Enter

notepad $PROFILE

Substitute notepad with your favorite text editor.

If the file exists, it will open the existing one, if it doesn’t it will create a new one at that location (usually it’s located in c:\users\[username]\documents\[Windows]PowerShell\Microsoft.PowerShell_profile.ps1 on Windows and $HOME/.config/powershell/Microsoft.PowerShell_profile.ps1 on Linux and MacOS))

Step 2: Add a function to your profile

function Set-Repo() {
	Param (
		[string] $Name
	)
	
	set-location "$($env:HOMEPATH)\repositories\$Name"
}

Save your profile file, and restart PowerShell. You can now enter Set-Repo -Name MyRepository and it will navigate you to c:\users\[yourusername]\repositories\MyRepository, Nice!

Tip: the HOMEPATH environment variable is set for you automatically. You can get a list of all environment variables in PowerShell by entering dir env:

Now, wouldn’t it be nice if we can use tab-completion in the cmdlet? E.g. enter ‘Set-Repo -Name My[tab]` and it would automatically complete the cmdlet with the correct repository name?

Let’s set that up.

Step 3: Adding tab completion

Just below the newly added function, add the following code:

$completionScriptBlock = 
{
	param($commandName, $parameterName, $stringMatch)
	Get-ChildItem "$($env:HOMEPATH)\repositories\$stringMatch*" -Directory | Select-Object -ExpandProperty Name
}

Register-ArgumentCompleter -Command "Set-Repo" -ParameterName Name -ScriptBlock $completionScriptBlock

This registers an argument completer for the Set-Repo cmdlet, and specifically for the -Name parameter. Everytime you press TAB in that parameter it will run the code in the scriptblock specified. In that scriptblock we basically return a list of all directory names of the repositories folder which PowerShell will use to show the options when you press TAB.

Step 4: Add an alias

The last step is that we add an alias that we can use, so instead of typing Set-Repo we want to be able to type repo. As a last line, add:

Set-Alias repo Set-Repo -Option AllScope

Save your profile file, restart PowerShell and you’re all set!