Shawn Melton – dbatools https://dbatools.io/ the community's sql powershell module Wed, 14 Mar 2018 13:03:46 +0000 en-US hourly 1 https://wordpress.org/?v=5.3.4 https://dbatools.io/wp-content/uploads/2016/05/dbatools.png?fit=32%2C32&ssl=1 Shawn Melton – dbatools https://dbatools.io/ 32 32 111052036 submitting an issue https://dbatools.io/new-issue/ https://dbatools.io/new-issue/#comments Wed, 14 Mar 2018 12:25:43 +0000 https://dbatools.io/?p=6825 An Issue Defined

In software development, an “issue” can be anything from you hit an error running an application or you get an unexpected result from an operation. You can also say an issue is a spelling error in our documentation. Our goal is to fix any “issue” whether it is a bug, an unexpected error (especially these) or considering a feature you think is missing from the module.

However, before we can fix it…you have to let us know.



 

Where to begin

This is purely based on what type of an issue you need to submit, but all of them will start by going to our repository and filling out an issue on GitHub. You can do this in 4 easy steps:

  1. Open your favorite browser, go to our GitHub issues shortlink [dbatools.io/issues](https://dbatools.io/issues)
  2. Click on the “Issues’ tab of the repository
  3. Take a minute or two and search the current issues (helps us to keep duplicate count low; if you find a match give it a thumbs up.)
  4. If you do not find anything in the current issues, click on “new issue” button and fill out a new one.

The remainder of this post is going to do a review of filling out a new issue. The more information you can provide helps our unpaid developers in getting a fix!

Before you start your new issue

Just like you submit a request to your own internal IT support, it helps to give as much information as you can up front when you submit an issue. Understand that this project is 100% community supported and we do this in our free time. If we get all the information up front, it is a huge time saver for us to fix the issue and return a resolution in a timely manner.

Feature Request

A feature that you want is to submit is basically: tell the story of what problem you are looking to solve. When you open a new issue we have a template setup. You can delete everything up to where you see the text ## Feature Request, below that, is where we need you to answer the question. Remember that even with a feature request the more details you can provide will help your cause in potentially getting the feature added.

What problem or scenario would you like to solve with dbatools?

This is the primary question we need you to answer for the feature you desire. We provide some header sections but you can add/remove those if it helps to organize your thoughts. We are not asking for an essay mind you but think of it as if you were going down an elevator with one of us, you have about 2-3 minutes to verbally explain what you wanted. Obviously, you can provide more information and detail, but consider putting that conversation down as a synopsis so we know where you are coming from and such.

Bugs and Errors

Bugs and errors are both a little different but in the area of submitting an issue, we will treat them the same for this post. While some errors may be expected we cannot really help you determine that unless you give us all the details. There are just some scenarios that you may find bugs and errors that we have not, or cannot account for due to limitations in our test lab(s). Every environment will be different and telling us about it all will aid in getting it fixed.

A few general steps

The top section of our issue template has 3 items that we ask you to verify, sometimes this can resolve your problem right off the bat…sometimes not.

Verified running the latest release of dbatools?

We push a new release to our master branch and the PowerShell Gallery on average every 2-3 days (based on when Chrissy’s on vacation). A release, on average, will always contain bug and error fixes, so just doing an Update-Module dbatools and restarting your PowerShell session may resolve your issue.

Verified errors are not related to permissions?

You would be surprised how often this can happen, so we have to ask. With the number of security issues, companies are having that affect their profits the whole least-privilege administration is more common nowadays. So if you know you are not sysadmin in SQL Server or local administrator if the command happens to touch the OS in some manner, it is a good thing to double-check before continuing.

Can duplicate in new/clean PowerShell session?

Not all modules play nice with each other. We have found in particular that the sqlserver module can cause issues with our module loading properly. So if you happen to import modules prior to or after importing dbatools, it helps to identify that none of those modules are adversely affecting dbatools execution.

Version and Edition information

Just the basics. This information is pivotal when we get down to debugging bugs and errors, helps to ensure we have a similar setup in our lab(s) to more closely get root cause. As well, we may identify flavors of each that may not play well together (e.g. credential prompts when using CIM/WMI). In particular, if you happen to be working with the migration commands (Copy-Dba* commands) or moving an object in some other process, it can help to include the version information for your source and destination/target.

Steps to Reproduce

Reproducible issues are the best kind, they also tend to be the ones that are the easiest to fix (tend to be mind you).

In order to reproduce the problem, we will need you to provide the command you are executing. If you can provide the values you are passing into the command it will help, but if for security reasons you cannot provide it all try to give some example values. You may also need to obfuscate the output from your PowerShell session if you want to provide screenshots.

Collecting logs and errors

We have added two commands to the module that can help us more quickly determine the issue if you are able to provide them.

Get-DbatoolsLog

This command simply outputs the messaging that has been generated since you imported the module into your session. This is one reason why duplicating your issue in a new/fresh console can help. Reissue the command and let the error or bug occur again, then run this command and you will see all the output generated from the command. This output includes an internal command that may have been executed as well.

New-DbatoolsSupportPackage

This command will generate a compressed file of collected information from the client machine, one you are using dbatools on. Think of this like you submit a support ticket to Microsoft support, they will have your run a few utilities on the offending machine to let it collect various logs and in-memory information. We do not capture as much as Microsoft, but information pertinent to the PowerShell session you have in use. I encourage you to run this and review the contents of that compressed file before attaching to an issue; ensure you are not violating any security policies.

Error record

This is a quick and dirty method and depends on the number of errors you may have encountered. PowerShell has a buffer or cache that errors from your PowerShell session are stored in. Checking this cache of errors right after you encounter an error will let you get the low down on what happened.

In order to see this you simply need to execute $error, that variable will contain the recent errors. To pull out the last error that happened you can run the following line:

$error[0] | Select-Object *

Closure

Just to give some closure…The process that follows once you submit an issue will on average be:

  1. One of the team will post the issue either verifying the information, providing some things to try, or confirming the issue.
  2. Once the issue is confirmed that a code change will be required, as time permits, a developer will take on getting the code fixed.
  3. You will see the issue closed either by the developer or once the change is committed to the master branch.

Thanks for reading,
Shawn 🇺🇸

]]>
https://dbatools.io/new-issue/feed/ 1 6825
VS Code and Task https://dbatools.io/vscode-task/ https://dbatools.io/vscode-task/#respond Fri, 09 Jun 2017 15:27:33 +0000 https://dbatools.io/?p=4669 While we are still hard at work getting everything ready for the 1.0 release, thought I would share something I figured out with VS Code. If you are not familiar with VS Code you can check the link out on how it is used to contribute to dbatools.

Pester

One of the big initiatives we are working fearlessly on for the module is getting the Pester test added and cleaned up. Appveyor is configured for the repository in GitHub so it will utilize the Pester test found in the tests folder. However, this also means that you, the developer, the ultimiate contributor, can utilize these test as you are working on a function.

Pester is a special syntax that lets you code in almost plain English. It is one of those that once it clicks you are like “where have you been all my life!”. If you are interested in learning more on Pester I’ve included a short list of some excellent resources to help:

Task in VS Code

Task in VS Code allow you to integrate external tools into your development process/cycle. So in PowerShell one of those is utilizing Pester to drive test driven development. (The Pester resources speak on this as writing your test before your functions.) If you are developing or writing code it can improve the process by periodically running your test to validate if you broke anything. This is dependent upon your test validating the code. You can fix as many of the bugs you can find now before it gets pushed out.

Right off I want to show a caveat for using Task:

Task in Code are only supported when you are working in a workspace folder.

A workspace is simply a folder of scripts/files, like the dbatools module. If you have dbatools open in VS Code, you can open the command palette (CTRL+SHIFT+P) and type task to see all the commands:

To generate the initial “task.json” file for your workspace just select the Task: Configure Task Runner. In the next prompt you can simply select Others.

Tasking

I will let you go through the documentation on task to get down to the nitty-gritty on the options you have in the syntax. I can tell you reading through that documentation will make the remainder of this post much more clear.

I generated the configuration for these task by using Plaster in VS Code. The PowerShell extension includes Plaster, which is a project around template-based project or module generation. When you build a module using Plaster for the first time it will ask you if you want to use Pester, and then proceeds to generate the task.json file for you. I simply took that file and expanded it. The repository for Plaster contains the initial file which only contains one task.

Our Task

The sample task that is generated comes with one simple task called Test, at this time. I renamed that task and then have added two additional task:

Task Purpose
Run.AllTest Runs every Pester test for the module.
Run.IntegrationTests Run all the Pester test but only those tagged as IntegrationTests.
Run.CurrentFile Will run the Pester test for for the function or file you have active/open, if one exist.

The full json file is provided at the end of this post. I wanted to just go over a few areas to help you understand what it is doing.

How do task Run?

As stated before a task allows you to run an external process, so our first step is to configure that external process. Which in our case is just the PowerShell.exe executable.

"_runner": "terminal", // (1) forces process to run in terminal panel, instead of the output
// Start PowerShell
"windows": {
// (2)  "command": "${env.windir}\\sysnative\\windowspowershell\\v1.0\\PowerShell.exe"
"command": "powershell.exe"
  1. This setting tells VS Code to run the task in the terminal panel and not the output. The output has no color by default so you don’t see all those pretty green and purple colors from Pester.
  2. The commented (“//”) command is what the initial file provides. It utilizes a predefined variable called env.windir, which does the same thing that $env:WINDIR does in PowerShell.

I had errors always showing in the terminal using the default path, about the PowerShell.exe not being found as a cmdlet. I realized that since I am running this in the terminal I am already in the context of the console so I only needed to call PowerShell.exe. Trying to reference the full path was causing the problem. I changed this to just powershell.exe and it cleaned up the initial errors.

Structure of a Task Configuration

"taskName": "Run.Something", //(1) referenced in command palette
"isTestCommand": false, // (2) if set to true it maps to "Task: Run Test Task"
"showOutput": "always", //(3) options are always, never, silent
"args": [
    "PS comands to run Invoke-Pester" // (4)
    ],
"problemMatcher": [
    "Some fancy regex to place output in the problem pane" //(5)
]

I will go over each part in the above example, but you can find more on each property in the documentation on schema for tasks.json. That document goes over each option and value.

  1. When you run the task command in the command palette, the taskName is displayed when you select to run a task.
  2. Setting isTestCommand to true will simply map the specific task to the command Task: Run Test Task in the command palette. You can also set that task command to a key binding if you want to save more time.
  3. If you want to see the output when it executes set showOutput to always. You can check the schema for what the other values will do.
  4. What is placed in args will be executed in the terminal window.
  5. The problemMatcher is the fancy part. This would be where you do some regex to parse the output to set if any of it is an issue (info, warning or error). This allows you to utilize the problem panel in VS Code, a shortcut to find the exact test that failed.

Test a Single Function

I wanted to have a task that would perform one main task for me: invoke the Pester test file for the current function.ps1 file I have open in VS Code. It took a bit to work this out, because I was not focusing on what was right in front of me. Once I figured that out I set the task isTestCommand property to true. This means you can easily validate your changes for a function by running the test just for that function and see if it passes or not. In the command palette that is select/typing Tasks: Run Test Task or you can map that to a key binding to make it more accessible.

"taskName": "Run.CurrentFile", // (1) name of the task
"suppressTaskName": true, // (2) don't want the task name as argument
"isTestCommand": true, // (3) map to run test task
"showOutput": "always", // (4) show the output and open terminal window each time
"args": [
    "Write-Host 'Invoking Pester' for ${fileBasename}; Invoke-Pester -PesterOption @{IncludeVSCodeMarker=$true} -Script '${workspaceRoot}/tests/${fileBasenameNoExtension}.Tests.ps1';",
    "Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
],

To burst your bubble up front: No you have to use Write-Host in this situation. Just like you do in Pester as well.

  1. The taskName I try to keep where the name explains what is being done. So simply named this one Run.CurrentFile.
  2. The supressTaskName prevents the it from being added as an extra argument, which in most cases can cause it to fail or error.
  3. I set isTestCommand to true so I can use the command palette shortcut. Again, you can also use key binding to make it easier.
  4. I’m setting showOutput to always because I want to see the output in the terminal window. I will show you the difference in setting this to false later.

The args is where the meat of it all sits. This section calls Invoke-Pester on the script found in the: root folder of the current workspace (dbatools repository folder), the test folder and then takes the name of the function file (minus the extension, .ps1) and appends .Tests.ps1 to it. So the end result if I run this task for Get-DbaDatabase would be dbatools\tests\Get-DbaDatabase.Test.ps1.

Task for specific Pester Test

The additional task I added was to have only the integration test executed for the whole module. In Pester you can organize your test using tags, and we utilize this by setting it to Integrationtests. So I can use the Invoke-Pester command to only go through all the test and just run those context blocks.

"Write-Host 'Invoking Pester'; Invoke-Pester -PesterOption @{IncludeVSCodeMarker=$true} -Tag 'Integrationtests';",
"Invoke-Command { Write-Host 'Completed Test task in task runner.' }"

The args value for this task is to simply use the -Tag parameter for Invoke-Pester and then pass it the tag I need to run. You can create additional task for each tag you use in your test if you wanted.

Example Run Test Task

I have intentionally changed a test for the Get-DbaDatabase function to show a passed test and a failed test. The video below illustrates the output you see in the terminal panel. It also shows that you can use the problem panel to see the exact test that failed with simpler output.

One additional thing you can do in both panels is click on the failed test and VS Code will open the test file and put your cursor on that test. In the terminal panel you have a URL link for the test file, so it will require the CTRL+ clicking on the link to open it up.

Full task.json file

// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${relativeFile}: the current opened file relative to workspaceRoot
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "_runner": "terminal",
    // Start PowerShell
    "windows": {
    //  "command": "C:\\WINDOWS\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"
    "command": "powershell.exe"
    },
//  "linux": {
//      "command": "/usr/bin/powershell"
//  },
//  "osx": {
//      "command": "/usr/local/bin/powershell"
//  },
    // The command is a shell script
    "isShellCommand": true,
    // Show the output window always
    "showOutput": "always",
    "args": [
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass"
    ],
    // Associate with test task runner
    "tasks": [
        {
            "taskName": "Run.AllTest",
            "suppressTaskName": true,
            "isTestCommand": false,
            "showOutput": "always",
            "args": [
                "Write-Host 'Invoking Pester'; Invoke-Pester -PesterOption @{IncludeVSCodeMarker=$true};",
                "Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
            ],
            "problemMatcher": [
                {
                    "owner": "powershell",
                    "fileLocation": [
                        "absolute"
                    ],
                    "severity": "error",
                    "pattern": [
                        {
                            "regexp": "^\\s*(\\[-\\]\\s*.*?)(\\d+)ms\\s*$",
                            "message": 1
                        },
                        {
                            "regexp": "^\\s+at\\s+[^,]+,\\s*(.*?):\\s+line\\s+(\\d+)$",
                            "file": 1,
                            "line": 2
                        }
                    ]
                }
            ]
        },
        {
            "taskName": "Run.IntegrationTests",
            "suppressTaskName": true,
            "isTestCommand": false,
            "showOutput": "always",
            "args": [
                "Write-Host 'Invoking Pester'; Invoke-Pester -PesterOption @{IncludeVSCodeMarker=$true} -Tag 'Integrationtests';",
                "Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
            ],
            "problemMatcher": [
                {
                    "owner": "powershell",
                    "fileLocation": [
                        "absolute"
                    ],
                    "severity": "error",
                    "pattern": [
                        {
                            "regexp": "^\\s*(\\[-\\]\\s*.*?)(\\d+)ms\\s*$",
                            "message": 1
                        },
                        {
                            "regexp": "^\\s+at\\s+[^,]+,\\s*(.*?):\\s+line\\s+(\\d+)$",
                            "file": 1,
                            "line": 2
                        }
                    ]
                }
            ]
        },
        {
            "taskName": "Run.CurrentFile",
            "suppressTaskName": true,
            "isTestCommand": true,
            "showOutput": "always",
            "args": [
                "Write-Host 'Invoking Pester' for ${fileBasename}; Invoke-Pester -PesterOption @{IncludeVSCodeMarker=$true} -Script '${workspaceRoot}/tests/${fileBasenameNoExtension}.Tests.ps1';",
                "Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
            ],
            "problemMatcher": [
                {
                    "owner": "powershell",
                    "fileLocation": [
                        "absolute"
                    ],
                    "severity": "error",
                    "pattern": [
                        {
                            "regexp": "^\\s*(\\[-\\]\\s*.*?)(\\d+)ms\\s*$",
                            "message": 1
                        },
                        {
                            "regexp": "^\\s+at\\s+[^,]+,\\s*(.*?):\\s+line\\s+(\\d+)$",
                            "file": 1,
                            "line": 2
                        }
                    ]
                }
            ]
        }
    ]
}
]]>
https://dbatools.io/vscode-task/feed/ 0 4669
Contributing with Code https://dbatools.io/vscode/ https://dbatools.io/vscode/#comments Thu, 02 Mar 2017 19:01:05 +0000 https://dbatools.io/?p=3601 What follows is a walk-through in getting VSCode setup for contributing to dbatools, and also includes various tips for utilizing the PowerShell Extension and Git features.

Install

VSCode is a cross-platform tool that works on Windows, Linux and Mac. You can download your specific OS flavor here. Just note that I only use Windows, so if you are on another OS your mileage may vary. If you favor being a beta tester you can download the Insiders Edition from the same page. The VSCode team made some visual cues to easily indicate what edition you are using, as they can be used side-by-side:

Editions

You will also need to download and install Git. If you already have GitHub Desktop installed, you will still need to install Git.

Where to Start

Getting started with VSCode can be a bit challenging at first if you normally use something like the PowerShell ISE. Just like any new tool it requires a bit of time to acclimate yourself to it. The documentation for VSCode is laid out well and was a big help for me getting started. I would encourage you to spend time going through, at a minimum, the following sections:

One additional resource that I think should be required reading, is the Tips and Tricks content that Microsoft published on GitHub.

Command Palette

I want to bring special attention to this because almost everything you can do via a menu or button in VSCode, can also be done via the command palette. The nice part of the palette is it will provide help along the way as you type. To open the command palette you can use the keyboard with CTRL+SHIFT+P or access it via the View menu.

Any extension that has commands is going to show in the format of “extension name: command”, so typing “powershell” will show any command that comes with the extension (once you install it). You can do the same thing for Git, just type that in and all the commands that are supported show up. There are additional commands outside of the extensions that are provided with VSCode, that I tend to use a good bit. I’ve included the most common below, along with the keyboard shortcut (if they have one):

  • Trim Trailing Whitespace (CTRL+K, CTRL+X)
  • Change Language Mode (CTRL+K, M)
  • Format Document (SHIFT+ALT+F)
  • Change All Occurrences (CTRL+F2)

Quick Open

CTRL+P provides a quick open prompt. This will list any recent file you have opened, but you can also use it to find a file within your current session of VSCode. So if you have a folder open with multiple files, just hit CTRL+P and start typing the file name. If a match is found it will be selected, you can just hit enter to open it.

Another feature is if you open a PS1 file that may have multiple functions in it, hit CTRL+P and then type the at symbol (“@”):

Settings

Extensions

The single item below is the only extension you truly need to start developing PowerShell in VSCode:

This extension provides the meat and potatoes for PowerShell.

Non-Administrator

The installation for VSCode would require you to have Administrator privileges. If you find you need to work without Administrator rights to install extensions you can try the manual method. VSCode extensions are just VSIX files so you can download the file and manually add it in VSCode. You will find the latest VSIX file on the extension’s release page on GitHub. You can get to that repository by searching GitHub or from the “Resources” section on the marketplace page. The file for the PowerShell extension will be named something similar to “PowerShell-x.x.x.vsix”.

Once you download the file just follow the steps below:

  1. Open the command palette.
  2. Type in “ext install from vsix” and hit enter
  3. Browse to the VSIX file you downloaded
  4. You will then receive a prompt to reload VSCode.

Code’s Settings

VSCode you work with files or folders. Opening a folder is equivalent to a project in Visual Studio. One thing to understand is adjusting the settings in VSCode can apply to the “user settings” or “workspace settings”. User Settings overwrite VSCode’s default settings, and Workspace Settings can overwrite User Settings.

Settings

Workspace Settings

Workspace settings apply to a folder you open with VSCode. When you open a folder and first open workspace settings you will see a new folder is added, “.vscode”. Any Extension or settings in VSCode you manipulate within your workspace settings will be saved under “.vscode\settings.json”.

The following are settings recommended (as a baseline) for contributing with dbatools. Just paste the below into the workspace settings. You can access it via the command palette, just start typing “Preferences”, and you will see “Open workspace settings” in the list.

// Place your settings in this file to overwrite default and user settings.
{
    "files.encoding": "utf8",
    "powershell.scriptAnalysis.enable": true,
    "powershell.scriptAnalysis.settingsPath": "bin//PSScriptAnalyzerRules.psd1",
    "powershell.codeFormatting.newLineAfterOpenBrace": true,
    "powershell.codeFormatting.openBraceOnSameLine": true,
    "editor.formatOnPaste": true,
    "editor.formatOnType": true,

    //tab format
    "editor.tabCompletion": true,
    "editor.tabSize": 4,
    "editor.insertSpaces": false,
    "editor.detectIndentation": true
    // Windows 8.1 and below require you to specify PowerShell for the Integrated Terminal
    // If you are also on another OS you will need to specify the path to PowerShell.exe
    "terminal.integrated.shell.windows": "C://WINDOWS//sysnative//WindowsPowerShell//v1.0//powershell.exe"
}

Clone dbatools repository

We first need to clone the repository before we can start contributing:

  1. Grab the “Clone with HTTPS” URL of your fork of dbatools.
  2. Open the command palette (CTRL + SHIFT + P)
  3. Type in “git clone” and press enter
  4. Paste the URL (CTRL + V) copied in step 1 into the prompt.
  5. Select the root folder where you want the repository to be kept (e.g C:\GitHub).

That is it! Once the repository is downloaded, VSCode will reload and open the dbatools folder. You can view the short recording to see the steps in action.

Add an Upstream

VSCode includes Git integration, which means you can use the command palette or the Git sidebar to perform Git commands within the same program. There are, however, some that are not supported at this time. In those cases you will need to revert to the command line or your tool of choice (e.g GitHub Desktop). If you favor the command line this is where the integrated terminal (CTRL+”backtick”) allows you to stay in VSCode.

When you fork dbatools to your GitHub account you will clone that repository, this is referred to as your “origin” remote. We just need to add another remote reference to the dbatools repository. This will make it a much smoother process to update your fork with the latest additions/modifications of dbatools.

Add upstream remote

The following command create a remote reference. You can name it whatever you want, but the standard term used with Git is “upstream”.

git remote add upstream https://github.com/dataplat/dbatools.git

After you run that command you can verify it was created as below:

remote upstream

Pull down updates

Once you have the remote that points to dbatools, you can use a few commands to pull down the changes. The following command updates all of the references to your remote repositories (origin and upstream).

git remote update

remote update

The development branch is the one all the changes to dbatools are initially committed to before making a release to master. You only really need to pull down the changes from this branch. The following command can be used for this purpose:

git pull upstream development

remote sync

The status bar in VSCode will show an indicator if any changes were pulled down.

remote sync

To show the breadth of VSCode with Git, there are 3 different ways you can “sync” your changes to your GitHub repository:

  1. Click on indicator in the status bar (the circle will start rotating)
  2. Open the command palette (CTRL+SHIFT+P), type “git sync” and hit enter.
  3. Open the Git sidebar, click on “…” at the top of the sidebar and click “sync”.

Branching Out

A branch is basically just a pointer to the current state of the current branch you have checked out. When you clone dbatools and open it in VSCode the first time should have the “development” branch checked out.

remote sync

If you create a branch from development, you are basically making a copy of that branch in the current state. If you want to checkout a different branch, just click on that branch name from the status bar. This is going to open the command palette with the “git checkout” command entered, this also causes the branches found on your origin and upstream remotes to be listed. You can then select which one you want, or start typing the name to filter the list.

remote sync

You can utilize the command palette to create a new branch as well, and is my preferred method. The following steps can be used:

  1. Open the command palette
  2. Type “git branch” and hit enter
  3. Provide your desired branch name and hit enter

After you hit enter you will see on the Git icon on the sidebar an icon shows it is working, once that goes away you will see the current branch change to your new branch.

branch indicator

After you create the branch you can see another indicator you can click on to publish the branch. You have to publish it before you can start making commits.

branch publish

When you click to publish the new branch, since we have multiple remotes, you will get a prompt to select which remote you want to publish the branch to, select “origin”.

branch remote select

Commit Often

It is often said “commit often” when you are using Git. It can help to make small changes, commit them, test them, and if something breaks roll-back that commit. VSCode offers you the basic ability of performing a commit but you can only roll back your last commit. So if you make a modification to a file you will see an indicator on the Git sidebar. Once you open that sidebar you can add your commit message and commit your change, all within VSCode.

remote sync

You can also right-click on any file listed in this sidebar to clean (remove any changes) and stage (make commits of only certain files at a time). If you open the file from the sidebar it will show you a comparison from your change and the original version of the file.

An Extra – Running PowerShell Code

If you are coming from the PowerShell ISE you may have gotten used to clicking the buttons on the toolbar to run either the whole script, or just the current line (or selected). In VSCode there are a few shortcomings in this area because there are no buttons. There are however key bindings/mappings that can be used.

Extensions – Keymaps

If you work with Atom or Sublime you can search the marketplace for “keymaps” and find a few extensions offered that will give you similar keybindings…note there is also one for Visual Studio.

Keybindings

By default the following keys are bound to the noted actions:

  • F5 – Starts debugging the current file (has to be saved with the ps1 extension)
  • F8 – Runs the currently focus (line or selected code).

There are a few caveats to the above keyboard bindings. The F8 keybinding runs the current line or selected code but outputs it to the Output pane and not the Integrated Terminal. If you go to your keyboard shortcuts, CTRL+K, CTRL+S and just paste the following to have it execute to the terminal:

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key": "f8",
        "command": "workbench.action.terminal.runSelectedText",
        "when": "editorTextFocus && editorLangId == 'powershell'"
    }
]

So a short example, open a new file add one or two PowerShell commands. You will need to open the Integrated Terminal, so a PowerShell session is running, and then just place the cursor on a line and hit F8.

VSCode F8

Now with F5 and debugging, it is up to you whether you want to change those around so they match up to what PowerShell ISE did. You would just need to find the command from the keyboard settings and add that to your keyboard settings.

An Extra-Extra – PSScriptAnalzyer

The PowerShell extension packages the PSScriptAnalyzer module which allows VSCode to check an open PS1 files against the PSSA rules. As the extension is released they bundle the latest version of the PSSA module. You can find what version is included by checking the following path on a Winodws machine:

# "x.x.x" is current version of the extension you have installed
$env:USERPROFILE\.vscode\extensions\ms-vscode.PowerShell-x.x.x\modules

PSSA performs checks based on best coding practices and identifies the line of code that violates them. You can view these by using “CTRL+SHIFT+M” to open the “Problems” pane. You also have an indicator on the bottom left of the status bar of VSCode (clicking this will also open the “Problems” pane.

Code problems pane

An added benefit as you open additional files, the problems pane will start grouping the problems by the file they are found in:

Code problems pane

Just click on one of the problems and VSCode will jump to that file and line.

Summary

While this post is a bit long it by no means covers all the features in VSCode. Read through the documentation to find out more that can be done. You can also search on YouTube for some good videos that show using code in various ways, generally with other languages. Happy contributing!

]]>
https://dbatools.io/vscode/feed/ 2 3601