Skip to content

Instantly share code, notes, and snippets.

@darfink
Last active April 24, 2021 16:47
Show Gist options
  • Save darfink/635d033bc0c608702895f0cd688be047 to your computer and use it in GitHub Desktop.
Save darfink/635d033bc0c608702895f0cd688be047 to your computer and use it in GitHub Desktop.
Windows WSL: CD into the most recently used explorer directory from bash
pfd() {
local windir="$(pwsh.exe -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass -Command - <<"EOF"
$Win32API = Add-Type -Name Funcs -Namespace Win32 -PassThru -MemberDefinition @'
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, IntPtr lpWindowName);
'@
$topmostHwnd = $Win32API::FindWindow('CabinetWClass', [IntPtr]::Zero)
$topmostWindow = (New-Object -COM 'Shell.Application').Windows() | Where-Object {$_.HWND -eq $topmostHwnd}
$topmostWindow.Document.Folder.Self.IsFileSystem ? $topmostWindow.Document.Folder.Self.Path : $null
EOF
)"
wslpath "$windir" | tr -d '\r'
}
cdf() {
cd "$(pfd)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment