Lately I have been on a PowerShell kick writing several utility functions. You can find my previous posts here:
In this post I am going to add one more that allows you to go up several levels in your path without having to repeatedly type .. over and over again. The new function is called Backup-Location with an alias of bu.
First, we need to create the function. To do that I started Visual Studio code. I also installed the PowerShell extension for Code.
With Code ready you need to create a new file and changed the language mode from Plain Text to PowerShell. If you already read my previous posts you can open the file we created in those posts. Copy and paste the code below into the file.
##############################################################################
#.SYNOPSIS
# Sets the location n number of levels up.
#
#.DESCRIPTION
# You no longer have to cd ..\..\..\..\ to move back four levels. You can now
# just type bu 4
#
#.PARAMETER Levels
# Number of levels to move back.
#
#.EXAMPLE
# PS C:\Users\dlbm3\source\pullrequests\somePR\vsteam> bu 4
# PS C:\Users\dlbm3>
##############################################################################
function Backup-Location {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[int] $Levels
)
$sb = New-Object System.Text.StringBuilder
for($i = 1; $i -le $Levels; $i++) {
$sb.Append("../") | Out-Null
}
Set-Location -Path $($sb.ToString())
}
Set-Alias bu Backup-Location
I got fancy this time and even added some help.
If you are continuing from my previous posts and used the same utils.ps1 file you are done.
If you are starting with this post, save the file so you we can dot source the file in our PowerShell profile. I named my file utils.ps1 and saved it in C:\Users\me\Documents\WindowsPowerShell\Scripts.
Now we must update our profile to dot source the file we just created. Start PowerShell and type the following:
code $Profile
This will start Code with your current profile script loaded or create a new file for you if you do not already have one.
Add to the bottom of the file
. C:\Users\me\Documents\WindowsPowerShell\Scripts\utils.ps1
Now just save and close the file. Now every new PowerShell session you start you will be able to use bu to navigate back several levels at a time.