Skip to content

Instantly share code, notes, and snippets.

@madd0
Created March 24, 2020 08:58
Show Gist options
  • Save madd0/7b6fcbec54044867fb42c37342819ada to your computer and use it in GitHub Desktop.
Save madd0/7b6fcbec54044867fb42c37342819ada to your computer and use it in GitHub Desktop.
A PowerShell function to easily navigate to a folder within a $BaseDir from anywhere using a dynamic parameter for tab completion. I use it to jump to repos in my `c:\sources` directory.
$BaseDir = "C:\sources"
Function go {
[CmdletBinding()]
param ()
DynamicParam {
# Set the dynamic parameters' name
$ParameterName = 'Repo'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet
$arrSet = Get-ChildItem $BaseDir\*, $BaseDir\*\* | Where-Object { $_.PSIsContainer } | Select-Object -Property Name,FullName
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet | Select-Object -ExpandProperty Name)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
begin {
# Bind the parameter to a friendly variable
$Repo = $PsBoundParameters[$ParameterName]
}
process {
$location = $arrSet | Where-Object { $_.Name -eq $Repo } | Select-Object -ExpandProperty FullName
Set-Location $location
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment