-
-
Save HeyItsGilbert/0f7e2febde87e74b554e6fab6a78e95b to your computer and use it in GitHub Desktop.
cd that: 1) navigates to parent folder when given a file path; 2) supports cd - to pop; 3) supports multiple parent changes with 2+ `.`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Set-LocationButBetter { | |
param ( | |
[Parameter( | |
ValueFromPipeline, | |
ValueFromPipelineByPropertyName | |
)] | |
$Path | |
) | |
process { | |
# Allows us to alias shortcuts | |
if($MyInvocation.BoundParameters.Count -eq 0){ | |
$Path = $MyInvocation.InvocationName | |
} | |
# If this contains 3 or more period, that means move up additional levels. | |
if($Path -match '^\.{2,}$'){ | |
$depth = $Path.Length | |
$path = Get-Location | |
# Start at 1 to treat the initial '..' as 1 parent. | |
for ($i = 1; $i -lt $depth; $i++) { | |
$path = (Split-Path $path -Parent) | |
} | |
} | |
if ($Path -eq '-'){ | |
Pop-location | |
} else { | |
if ([System.IO.File]::Exists($Path)) { | |
Push-Location (Split-Path $Path -Parent) | |
} | |
else { | |
Push-Location $Path | |
} | |
} | |
} | |
} | |
Remove-Item alias:cd | |
Set-Alias -Name cd -Value Set-LocationButBetter | |
Set-Alias -Name .. -Value Set-LocationButBetter | |
Set-Alias -Name ... -Value Set-LocationButBetter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also this does something I usually forbid: overwrite a param variable. But it's Good Enough