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?
(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"}
}
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