PoshCode Archive  Artifact [7f143f6b3b]

Artifact 7f143f6b3b1a760372fe32cb8ebcc52eec178a00cccc2e283720ea1283dc133d:

  • File Add-RelativePathCapture.ps1 — part of check-in [8c77eb2bc2] at 2018-06-10 13:05:32 on branch trunk — From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes (user: Lee Holmes size: 1793)

# encoding: ascii
# api: powershell
# title: Add-RelativePathCapture.
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 2131
# x-archived: 2016-05-17T08:24:18
# x-published: 2011-09-09T21:40:00
#
#
##############################################################################
##
## Add-RelativePathCapture
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Adds a new Out-Default command wrapper that captures relative path
navigation without having to explicitly call 'Set-Location'

.EXAMPLE

PS C:\Users\Lee\Documents>..
PS C:\Users\Lee>...
PS C:\>

.NOTES

This commands builds on New-CommandWrapper, also included in the Windows
PowerShell Cookbook.

#>

Set-StrictMode -Version Latest

New-CommandWrapper Out-Default `
    -Process {
        if(($_ -is [System.Management.Automation.ErrorRecord]) -and
            ($_.FullyQualifiedErrorId -eq "CommandNotFoundException"))
        {
            ## Intercept all CommandNotFound exceptions, where the actual
            ## command consisted solely of dots.
            $command = $_.TargetObject
            if($command -match '^(\.)+$')
            {
                ## Count the number of dots, and go that many levels (minus
                ## one) up the directory hierarchy.
                $newLocation = "..\" * ($command.Length - 1)
                if($newLocation) { Set-Location $newLocation }

                ## Handle the error
                $error.RemoveAt(0)
                $_ = $null
            }
        }
    }