VS Code - Shortcut to change the current directory in the PowerShell console to the currently opened file? [duplicate] - powershell

This question already has answers here:
How to quickly change shell folder to match the currently open file
(5 answers)
Closed 3 years ago.
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?

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.

Related

How to open a file from the integrated terminal in VSCode to a new tab

If my script is run within vscode, it want it to open a .txt file in a new tab in vscode. Else, open the folder containing the file. However, the current "code" command opens it in the terminal window instead of a new edit tab.
if ($env:TERM_PROGRAM -eq 'vscode') {
code 'C:\temp\_Release_Evidence\test.txt'
}
else {
explorer 'C:\temp\_Release_Evidence'
}
Normally, code refers Visual Studio Code's CLI, which is assumed to be in one of the directories listed in $env:PATH:
On Windows, it refers to the code.cmd batch file that serves as the CLI entry point.
On Unix-like platforms it refers to a code Bash script.
Its default behavior is to open a given file as a new tab in the most recently activated Visual Studio Code window (which, when run from inside Visual Studio Code, is by definition the current window).
If that doesn't happen for you, perhaps code refers to a different executable on your machine:
To avoid ambiguity, use the full CLI path instead, which, however, requires you to know Visual Studio Code's install location; typical CLI locations are:
Windows: $env:LOCALAPPDATA\Programs\Microsoft VS Code\bin\code.cmd
macOS: /usr/local/bin/code
Linux: /usr/bin/code
On Windows, something as simple as including the filename extension in the invocation - i.e., code.cmd - may help.
However, assuming you're using the PIC (PowerShell Integrated Console), a specialized PowerShell shell that comes with the PowerShell extension for Visual Studio Code, a workaround that also performs better, because it doesn't require launching a child process:
The PIC comes with the psedit command (an alias for the Open-EditorFile function), which quickly opens one or more files in a tab in the current Visual Studio Code window.
Caveat: As of version v2022.5.1 of the PIC, specifying multiple files only works meaningfully if they are individually enumerated, as literal paths. If you try to use a wildcard pattern or a directory path, all matching files / files in the directory are uselessly opened in sequence in a single tab.
Thus, you could use the following:
if ($env:TERM_PROGRAM -eq 'vscode') {
# Use `psedit`, if available; `code` otherwise.
$exe = if ((Get-Command -ErrorAction Ignore psedit)) { 'psedit' } else { 'code' }
& $exe 'C:\temp\_Release_Evidence\test.txt'
}
else {
explorer 'C:\temp\_Release_Evidence'
}
I can't reproduce this or explain why this might occur on your system. Running the following whether in the PowerShell Integrated Terminal (which #mklement0 explained succinctly) or a standard PowerShell terminal in VS Code's Terminal pane should open the file in a new tab where file contents are normally displayed:
code /path/to/file.txt
A suitable workaround may be to get the contents of a text file and pipe them in via STDIN. We can do this by adding a hyphen - as an empty parameter to code when piping data to it:
# Tip: Use the gc alias for Get-Content
Get-Content /path/to/file.txt | code -
You can then use Save As... to save the file to its intended target once you make your changes. You will need to use Ctrl+C in the terminal to close the input stream if you need to run additional commands before closing the file or saving to a one.
Even if this isn't a suitable workaround for you, it's a handy tip in other scenarios. For example, the following command will open documentation for Get-Process inside VSCode:
Reminder: Don't forget to hit Ctrl+C in the terminal once the content finishes populating to be able to run additional commands, or close the temporary file buffer.
Get-Help Get-Process -Detailed | code -

Is it possible to get the full file name of the file you have open/are viewing in VS Code via the integrated Terminal?

In the VS Code terminal, is there a command that will give you the name of the file that you currently have open? e.g. just the file name IndexController.php?
I frequently run a test command in my terminal make test-watch /long/path/to/file.php and I need to right click on the file name and select "copy relative path" to get that path, which I then have to paste in.
It would save me a little bit of hassle if I could add a make test-watch-here that just read from the open file. Is it possible?
You can use the extension Command Variable v1.19.0
With the command extension.commandvariable.inTerminal you can type the result of a command in the terminal.
The extension contains also a command to transform a string with variables to there value.
An example for your case:
{
"key": "ctrl+i f5", // or any other combo
"command": "extension.commandvariable.inTerminal",
"args": {
"command": "extension.commandvariable.transform",
"args": { "text": "${relativeFile}" }
}
}
The key combo works in the editor and the terminal.
See the doc of the extension to see what you can do more with the transform command (like find/replace with regexp)

How to clear the entire terminal (PowerShell)

I had an issue. Using the clear or cls command in powershell clears only the visible portion of the terminal,I would like to know how to clear the entire terminal?
I use VSCode by the way.
To also clear the scrollback buffer, not just the visible portion of the terminal in Visual Studio Code's integrated terminal, use one of the following methods:
Use the command palette:
Press Ctrl+Shift+P and type tclear to match the Terminal: Clear command and press Enter
Use the integrated terminal's context menu:
Right-click in the terminal and select Clear from the context menu.
On Windows, you may have to enable the integrated terminal's context menu first, given that by default right-clicking pastes text from the clipboard:
Open the settings (Ctrl+,) and change setting terminal.integrated.rightClickBehavior to either default or selectWord (the latter selects the word under the cursor before showing the context menu).
Use a keyboard shortcut from inside the integrated terminal (current as of v1.71 of VSCode):
On macOS, a shortcut exists by default: Cmd+K
On Linux and Windows, you can define an analogous custom key binding, Ctrl+K, as follows, by directly editing file keybindings.json (command Preferences: Open Keyboard Shortcuts (JSON) from the command palette), and placing the following object inside the existing array ([ ... ]):
{
"key": "ctrl+k",
"command": "workbench.action.terminal.clear",
"when": "terminalFocus && terminalHasBeenCreated || terminalFocus && terminalProcessSupported"
}
Using a command you can invoke from a shell in the integrated terminal:
Note: A truly cross-platform solution would require executing the VSCode-internal workbench.action.terminal.clear command from a shell, but I don't know how to do that / if it is possible at all - do tell us if you know.
Linux (at least as observed on Ubuntu):
Use the standard clear utility (/usr/bin/clear), which also clears the scrollback buffer.
From PowerShell, you may also use Clear-Host or its built-in alias, cls.
By contrast, [Console]::Clear() does NOT clear the scrollback buffer and clear just one screenful.
macOS:
Unfortunately, neither /usr/bin/clear nor PowerShell's Clear-Host (cls) nor .NET's [Console]::Clear() clear the scrollback buffer - they all clear just one screenful.
Print the following ANSI control sequence: '\e[2J\e[3J\e[H' (\e represents the ESC char. (0x1b, 27); e.g., from bash: printf '\e[2J\e[3J\e[H'; from PowerShell: "`e[2J`e[3J`e[H"
You can easily wrap this call in a shell script for use from any shell: create a file named, say, cclear, in a directory listed in your system's PATH variable, then make it executable with chmod a+x; then save the following content to it:
#!/bin/bash
# Clears the terminal screen *and the scrollback buffer*.
# (Needed only on macOS, where /usr/bin/clear doesn't do the latter.)
printf '\e[2J\e[3J\e[H'
Windows:
NO solution that I'm aware of: cmd.exe's internal cls command and PowerShell's internal Clear-Host command clear only one screenful in the integrated terminal (not also the scrollback buffer - even though they also do the latter in a regular console window and in Windows Terminal).
Unfortunately, the escape sequence that works on macOS ("`e[2J`e[3J`e[H" or, for Windows PowerShell, "$([char]27)[2J$([char]27)[3J$([char]27)[H") is not effective: on Windows it just clears one screenful.
(By contrast, all of these methods do also clear the scrollback buffer in regular console windows and Windows Terminal.)
right click on the powershell button,
then select clear,
when you are at the command window, type "clear" command, to clear the terminal window.

How to I remove the Powershell start text?

Powershell 6 has a Unix-style /etc/issue that mentions a link to the docs.
PowerShell v6.0.0
Copyright (c) Microsoft Corporation. All rights reserved.
https://aka.ms/pscore6-docs
Type 'help' to get help.
This is fine, but:
I know where the docs are
I know I launched Powershell 6
How can I remove some, or all of the message? IIRC Powershell 5 still had the copyright message so maybe I can't remove that, but getting rid of the last 3 lines would help?
Pass the -nologo option.
-NoLogo Starts the PowerShell console without displaying the copyright banner.
pwsh.exe -nologo ...other arguments...
If you are using the new Windows Terminal then:
Go to Settings:
Add the argument -nologo to the PowerShell command line:
From #sandu's answer, it could be improved as below.
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"args": ["-noLogo"]
}
},
"terminal.integrated.defaultProfile.windows": "PowerShell",
Now you can add -nologo in Windows Terminal settings:
The easiest way would be to add Clear-Host to the top of your $profile file.
You can open powershell and input $profile, you will get Microsoft.PowerShell_profile.ps1 file's path.
open this file (create one without) by notepad and input a clear or cls command.Save and exit.
the command of this file will be executed when you open powershell
As np8 said under this answer, the way to hide the initial text in the Visual Studio Code integrated terminal is as follows:
Open the workspace settings file (./.vscode/settings.json) or the user settings file (search for Preferences: Open Settings (JSON) in the command palette, opened with F1)
Add the following inside the outer-most "layer" of curly brackets:
"terminal.integrated.shellArgs.windows": [
"-nologo"
]
What worked for me was to go to File > Preferences > Settings and type terminal.integrated.defaultProfile.windows in the search bar (you can change windows with other supported OS if you need to). There should now be only one option to choose from (that's why I included windows). Click on the Edit in settings.json link bellow it. It should now open settings.json and generate the line necessary to modify the default terminal profile. Which looks something like:
"terminal.integrated.defaultProfile.windows": "",
Above that line you can create your own profile:
"terminal.integrated.profiles.windows": {
"PowerShell -nologo": {
"source": "PowerShell",
"args": ["-nologo"]
}
},
Name the profile however you want and add whatever parameters you want. Once you're done. Set the profile name into the option that was previously generated for you. In this example it should look like:
"terminal.integrated.defaultProfile.windows": "PowerShell -nologo",
Save and close. Now when you open a terminal it should have no logo for example.
I was fix problem on the top by
There are several ways of doing it :
Creating a shortcut with value
"C:\Program Files\PowerShell\7\pwsh.exe" -nologo -NoExit -Command "Set-Location c:\Users\%username%"
If you are using Windows terminal then you can replace the source with
"commandline": "pwsh.exe -NoLogo"
Users of Chinese version can also add -nologo in Windows terminal settings:
As shown in the figure:
If you are using the new Windows Terminal in Windows 11,
Go to Settings:
Select the Windows Powershell profile from the left sidebar
Add the argument -nologo to the command line:
Save and be sure to restart your terminal to see the changes.
If you're using windows just create a profile and put the command clear inside it.
In PowerShell I'm going to open the profile with notepad:
notepad $Profile
Highly Recommended to Use
Powershell Preview: https://github.com/PowerShell/powershell/releases
Editing Context Menu
If you are using Powershell Preview, you can change context menu using regedit:
Open regedit
Go to Computer\HKEY_CLASSES_ROOT\Directory\Background\shell\PowerShell7-previewx64
add flag -nologo to Icon
2. Editing Start Menu Shortcut
In File Explorer go to
C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
Create a shortcut with value
"C:\Program Files\PowerShell\7-preview\pwsh.exe" -nologo -NoExit -Command "Set-Location c:\\Users\\%username%"

How to change the integrated terminal in Visual Studio code

I want to change integrated terminal to CMDER i use VS Code on Windows 8.1.
I checked the docs and also preference file, but I am confused
which line to change.
External Terminal
// Customizes which terminal to run on Windows.
"terminal.external.windowsExec": "%COMSPEC%",
// Customizes which terminal application to run on OS X.
"terminal.external.osxExec": "Terminal.app",
// Customizes which terminal to run on Linux.
"terminal.external.linuxExec": "xterm",
Integrated Terminal
// The path of the shell that the terminal uses on Linux.
"terminal.integrated.shell.linux": "sh",
// The command line arguments to use when on the Linux terminal.
"terminal.integrated.shellArgs.linux": [],
// The path of the shell that the terminal uses on OS X.
"terminal.integrated.shell.osx": "sh",
// The command line arguments to use when on the OS X terminal.
"terminal.integrated.shellArgs.osx": [],
// The path of the shell that the terminal uses on Windows. When using shells shipped with Windows (cmd, PowerShell or Bash on Ubuntu), prefer C:\Windows\sysnative over C:\Windows\System32 to use the 64-bit versions.
"terminal.integrated.shell.windows": "C:\\Windows\\system32\\cmd.exe",
// The command line arguments to use when on the Windows terminal.
"terminal.integrated.shellArgs.windows": [],
// Controls the font family of the terminal, this defaults to editor.fontFamily's value.
"terminal.integrated.fontFamily": "",
// Controls whether font ligatures are enabled in the terminal.
"terminal.integrated.fontLigatures": false,
// Controls the font size in pixels of the terminal, this defaults to editor.fontSize's value.
"terminal.integrated.fontSize": 0,
// Controls the line height of the terminal, this number is multipled by the terminal font size to get the actual line-height in pixels.
"terminal.integrated.lineHeight": 1.2,
// Controls whether the terminal cursor blinks.
"terminal.integrated.cursorBlinking": false,
// Controls whether locale variables are set at startup of the terminal, this defaults to true on OS X, false on other platforms.
"terminal.integrated.setLocaleVariables": false,
// A set of command IDs whose keybindings will not be sent to the shell and instead always be handled by Code. This allows the use of keybindings that would normally be consumed by the shell to act the same as when the terminal is not focused, for example ctrl+p to launch Quick Open.
"terminal.integrated.commandsToSkipShell": [
"editor.action.toggleTabFocusMode",
"workbench.action.debug.continue",
"workbench.action.debug.restart",
"workbench.action.debug.run",
"workbench.action.debug.start",
"workbench.action.debug.stop",
"workbench.action.quickOpen",
"workbench.action.showCommands",
"workbench.action.terminal.clear",
"workbench.action.terminal.copySelection",
"workbench.action.terminal.focus",
"workbench.action.terminal.focusNext",
"workbench.action.terminal.focusPrevious",
"workbench.action.terminal.kill",
"workbench.action.terminal.new",
"workbench.action.terminal.paste",
"workbench.action.terminal.runSelectedText",
"workbench.action.terminal.scrollDown",
"workbench.action.terminal.scrollDownPage",
"workbench.action.terminal.scrollToBottom",
"workbench.action.terminal.scrollToTop",
"workbench.action.terminal.scrollUp",
"workbench.action.terminal.scrollUpPage",
"workbench.action.terminal.toggleTerminal"
],
To change the integrated terminal on Windows, you just need to change the terminal.integrated.shell.windows line:
Open VS User Settings (Preferences > User Settings). This will open two side-by-side documents.
Add a new "terminal.integrated.shell.windows": "C:\\Bin\\Cmder\\Cmder.exe" setting to the User Settings document on the right if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.
Save the User Settings file.
You can then access it with keys Ctrl+backtick by default.
It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).
To do so:
Create an environment variable "CMDER_ROOT" pointing to your Cmder
directory.
In (Preferences > User Settings) in VS Code add the following settings:
"terminal.integrated.shell.windows": "cmd.exe"
"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]
I know is late but you can quickly accomplish that by just typing Ctrl+Shift+P and then type "default" - it will show an option that says:
Terminal: Select Default Shell
It will then display all the terminals available to you.
From Official Docs
Correctly configuring your shell on Windows is a matter of locating
the right executable and updating the setting. Below is a list of
common shell executables and their default locations.
There is also the convenience command Select Default Shell that can be
accessed through the command palette which can detect and set this for
you.
So you can open a command palette using ctrl+shift+p, use the command Select Default Shell, then it displays all the available command line interfaces, select whatever you want, VS code sets that as default integrated terminal for you automatically.
If you want to set it manually find the location of executable of your cli and open user settings of vscode(ctrl+,) then set
"terminal.integrated.shell.windows":"path/to/executable.exe"
Example for gitbash on windows7:
"terminal.integrated.shell.windows":"C:\\Users\\stldev03\\AppData\\Local\\Programs\\Git\\bin\\bash.exe",
For OP's terminal Cmder there is an integration guide, also hinted in the VS Code docs.
If you want to use VS Code tasks and encounter problems after switch to Cmder, there is an update to #khernand's answer. Copy this into your settings.json file:
"terminal.integrated.shell.windows": "cmd.exe",
"terminal.integrated.env.windows": {
"CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
"/k",
"%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
// OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],
The invoked file will open Cmder as integrated terminal and switch to cmd for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json to make tasks work.
Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows" setting, which lets you set your terminal for tasks globally and avoids issues with Cmder.
"terminal.integrated.automationShell.windows": "cmd.exe"
I was successful via settings > Terminal > Integrated > Shell: Linux
from there I edited the path of the shell to be /bin/zsh from the default /bin/bash
there are also options for OSX and Windows as well
#charlieParker - here's what i'm seeing for available commands in the command pallette
If you want to change the external terminal to the new windows terminal, here's how.
The method explained in the accepted answer has been deprecated, now the new recommended way to configure your default shell is by creating a terminal profile in #terminal.integrated.profiles.windows# and setting its profile name as the default in #terminal.integrated.defaultProfile.windows#.
The old method will currently take priority over the new profiles settings but that will change in the future.
See an example for powershell taken from the docs
{
"terminal.integrated.profiles.windows": {
"My PowerShell": {
"path": "pwsh.exe",
"args": ["-noexit", "-file", "${env:APPDATA}PowerShellmy-init-script.ps1"]
}
},
"terminal.integrated.defaultProfile.windows": "My PowerShell"
}
change external terminal
windows terminal , which has been mentioned by others, is an alternative of alacrity, which is a terminal (emulator)
As stated in vscode, Cmder is a shell, just like powershell or bash.
"terminal.integrated.profiles.windows": {
"cmder": {
// "path": "F:\\cmder\\Cmder.exe", // 这样会开external terminal
"path": "C:\\WINDOWS\\System32\\cmd.exe",
"args": ["/K", "F:\\cmder\\vendor\\bin\\vscode_init.cmd"]
}
},
"terminal.integrated.profiles.linux": { "zsh": { "path": "zsh" }, },
"terminal.integrated.defaultProfile.windows": "PowerShell",
The statment in cmder' repo is misleading
Different shells under a terminal:
If you want to change the external terminal to the new windows terminal, here's how.
Probably it is too late but the below thing worked for me:
Open Settings --> this will open settings.json
type terminal.integrated.windows.shell
Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
Set the value as terminal.integrated.windows.shell: C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
Click Ctrl + S
Try to open new terminal. It should open in bash editor in integrated mode.
Working as of 02-Dec-2021.
In settings.json
{
"go.toolsManagement.autoUpdate":true,
"terminal.integrated.profiles.windows":{
"My Bash":{
"path":"D:\\1. Installed_Software\\Git\\bin\\bash.exe"
}
},
"terminal.integrated.defaultProfile.windows":"My Bash"
}
Reference: https://code.visualstudio.com/docs/editor/integrated-terminal#_terminal-profiles