Go to specific parent directory with PowerShell

After typing commands similar to  ‘cd ..\..\..\’ a few too many times, I needed a better solution.

My first idea was to have something like cd… and depending on the number of dots go up to the nth parent. Still, I’d have to count how many directories up my target is.

A colleague of mine had a better idea:

Lets say you are in
C:\Users\JoeShmoe\Documents\Books\
and you would like to go to
c:\Users.
Ideally you just type something like ‘cdto users‘ or even ‘cdto u

 

It would indeed be dandy to have such a function, so I invested some time and came up with the below implementation.


<#
    .Synopsis
        Sets location to the first parent directory that whose name starts with the given target dir.
    .Description
        Searches upwards to the root drive.
        If target dir is not found, a message is emitted to the console
    .Example
        cd c:\user\joeshmoe\Documents 
        C:\user\joeshmoe\Documents>
        Set-LocationTo us 
        C:\user>
#>            
            
function Set-LocationTo {            
    param(  [parameter(Mandatory = $true)]            
         [ValidateNotNullOrEmpty()]            
            [string] $targetDir)            
            
    $dirs = (pwd).Path.Split('\')            
    for($i = $dirs.Length - 1; $i -ge 0; $i--) {            
        if ($dirs[$i].ToLower().StartsWith($targetDir.ToLower())) {            
            $targetIndex = $i            
            break            
        }            
    }            
    if($targetIndex -eq 0) {             
        Write-Host "Unable to resolve $targetDir"             
        return            
    }            
            
    $targetPath = ''            
    for($i = 0; $i -le $targetIndex; $i++) {            
       $targetPath += $dirs[$i] + '\'             
    }            
            
    Set-Location $targetPath            
}            
            
Set-Alias -Name cdto -Value Set-LocationTo
            

If you are sourcing this Set-Location.ps1 from within a module, make sure to export aliases as well e.g.:



Export-ModuleMember -Function * -Alias *


otherwise ‘cdto’ won’t be available.

Advertisements
  1. Go to specific parent directory with PowerShell » Lab49 Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: