powershellvisual-studio-codevscode-keybinding

Configure VS Code keybinding to open a new Powershell script?


I have the MS Powershell extension installed in VS Code. Other language extensions, e.g. Python, have the ability to assign a keybinding for creating a new file (python.createNewFile). I don't see this option in the Powershell extension. There isn't even an option with Ctrl-Shift-P.

EDIT: Expanding on the Python example, using a keybinding sequence for python.createNewFile will create a new file that already has Python syntax highlighting defined. I don't have to create the file, then save it with a .py extension to achieve this. I can get right into the scripting. I'd like to be able to do the same with Powershell.

The only options I have at the moment are to Ctrl + N, Ctrl + S, and give it a file name with a .ps1 extension, or Ctrl + N and choose "Powershell" from the Select a Language list.

Is there another way to do this? A macro or something? There are other Powershell extensions, but as far as I can tell the only way to know the abilities they provide, is to install each one.


Solution

  • You can place an adapted version of the following in your keybindings.json file:

      // Be sure to place this inside the overall enclosing [...]
      // and, if other objects are present, place a "," before/after
      // it to ensure that all objects are ","-separated.
      {
        "key": "shift+f12", // adapt as needed
        "command": "workbench.action.files.newUntitledFile",
        "args": {
          "languageId": "powershell"
        }
      }
    

    Thereafter, pressing Shift+F12 will open a new, untitled file and set its language mode to PowerShell, which entails:


    Optional reading: How to discover Visual Studio Code's available API commands:

    [1] Neither does the Gist you mention in a comment, whose results are based on authoring a dummy extension (and seemingly includes non-public commands, prefixed with _). The results there are a snapshot of the available commands at a given point in time. Fellow users have provided updated snapshots over time, but using the methods described above is preferable, as they are guaranteed to be current for a given Visual Studio Code installation.