UPDATE: This is the best solution so far
(Thanks to Mark in the comments of the original post.)
In the keybindings.json file, add the following key binding:
{
"key": "ctrl+alt+d",
"command": "workbench.action.terminal.sendSequence",
"args": {"text": "cd \"${fileDirname}\"\u000D"}
}
This works in both cmd and PowerShell consoles.
(The only flaw is that it does not change the directory across drives for the cmd console only).
UPDATE 2:
A new command will be added in v1.39 workbench.action.terminal.newWithCwd
, see add terminal here command. The example keybinding given is:
{
"key": "cmd+shift+h",
"command": "workbench.action.terminal.newWithCwd",
"args": {
"cwd": "${fileDirname}"
}
}
This will create a new terminal, not change the current terminal.
Previous answer
Credit goes to SeeminglyScience for this answer.
There is not currently a way to set a keyboard shortcut, but since that is not explicitly stated in the title, I will post another shortcut.
If you do not already have a file called Microsoft.VSCode_profile.ps1 in your "%UserProfile%\Documents\WindowsPowerShell" directory, create one.
Create a custom PowerShell editor command by adding the following to the Microsoft.VSCode_profile.ps1 file:
Register-EditorCommand -Name 'ChangeDirHere' -DisplayName 'Change to the Directory of the Current File' -ScriptBlock {
Set-Location ([System.IO.Path]::GetDirectoryName($psEditor.GetEditorContext().CurrentFile.Path))
}
Restart VS Code.
- Open any PowerShell file.
- Press Alt+Shift+S (or whatever keybinding you have for "Powershell: Show Additional Commands from PowerShell Modules").
- Select the custom command from the drop-down list of PowerShell commands.