Skip to content

Instantly share code, notes, and snippets.

@HeyItsGilbert
Forked from nohwnd/cd.ps1
Last active January 14, 2025 20:52
Show Gist options
  • Save HeyItsGilbert/0f7e2febde87e74b554e6fab6a78e95b to your computer and use it in GitHub Desktop.
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+ `.`
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
@HeyItsGilbert
Copy link
Author

Also this does something I usually forbid: overwrite a param variable. But it's Good Enough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment