Vscode-powershell: Shortcut to change the current directory in the PowerShell console to the currently opened file?

Created on 18 Sep 2019  路  5Comments  路  Source: PowerShell/vscode-powershell

I am running the PowerShell extension in Visual Studio Code with its PowerShell Integrated Console attached. I have two PowerShell scripts each open in separate tabs. The files are located in different directories.

I would like to quickly change the current directory to the currently active tab in the PowerShell console using a keyboard shortcut (e.g. Ctrl+Alt+D).

How does one accomplish this?

https://stackoverflow.com/questions/57893791

Most helpful comment

I found a better solution from StackOverflow that works in both the cmd and PowerShell consoles. (Better because it is a keyboard shortcut and not a menu selection.)

In the keybindings.json file, add the following key binding:

{
"key": "ctrl+alt+d",
"command": "workbench.action.terminal.sendSequence",
"args": {"text": "cd \"${fileDirname}\"\u000D"}
}

https://stackoverflow.com/questions/57893791

All 5 comments

(NOTE: All of this code must be run in the PowerShell Integrated Console)

You would do it like this in script:

Set-Location ([IO.Path]::GetDirectoryName($PSEditor.GetEditorContext().CurrentFile.Path))

You could register an Editor Command to be quick about it:

Register-EditorCommand -Name ChangeToDir -DisplayName "Change to the Directory of the Current File" -ScriptBlock {
    Set-Location ([IO.Path]::GetDirectoryName($PSEditor.GetEditorContext().CurrentFile.Path))
}

Then you can do:

cmd+shift+s (or ctrl+shift+s on non-macOS I think)

Then find "Change to the Directory of the Current File" in the list!

Thank you for the response. It works.

Is there no way to assign a keyboard shortcut directly to "ChangeToDir"?

Not currently due to #2145, but after that's fixed it'll be possible.

Thank you

I found a better solution from StackOverflow that works in both the cmd and PowerShell consoles. (Better because it is a keyboard shortcut and not a menu selection.)

In the keybindings.json file, add the following key binding:

{
"key": "ctrl+alt+d",
"command": "workbench.action.terminal.sendSequence",
"args": {"text": "cd \"${fileDirname}\"\u000D"}
}

https://stackoverflow.com/questions/57893791

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timoline picture timoline  路  3Comments

nathan-alden-hp picture nathan-alden-hp  路  3Comments

MiYanni picture MiYanni  路  3Comments

rkeithhill picture rkeithhill  路  3Comments

CJHarmath picture CJHarmath  路  3Comments