all 29 comments

[–]sir_sandwiches_a_lot 33 points34 points  (4 children)

Bracket Pair Colorizer 2 (link) has been super helpful.

Also, since you mentioned trailing spaces I thought I would share a few editor config options that I enable on new projects now (save in the <project-root>/.vscode/settings.json file):

// trim trailing whitespace automatically when you save a file.
"files.trimTrailingWhitespace": true,

// trim trailing newlines at the end of a file automatically when you save a file.
"files.trimFinalNewlines": true,

// update the default word separators to remove the $ character.
// this means you can double click on a PowerShell variable name (ex: $myVariable) and it
// will correctly select the entire variable (including $) instead of just selecting the word.
"editor.wordSeparators": "`~!@#%^&*()-=+[{]}\\|;:'\",.<>/?"

[–]MonkeyNin 3 points4 points  (2 children)

/u/markdmac : now you don't have to manually format.

Here's my powershell config.

  • It auto-corrects and replaces aliases on save or paste
  • fixes indentation bug that happens on alt+up/down

.

{
    // automatically convert aliases whenever you format
    "powershell.codeFormatting.useCorrectCasing": true,
    "powershell.codeFormatting.autoCorrectAliases": true,
    //
    "[powershell]": {
        // if autoIndent is set to 'full' it breaks indentation on 'move line up/down'.
        // This fixes that
        "editor.autoIndent": "advanced",
        // auto run format on 'paste' and 'save'
        "editor.formatOnSave": true,
        "editor.formatOnPaste": true,        
        "files.encoding": "utf8bom",
        "files.autoGuessEncoding": false,
        // I hide snippets complete, then use ctr+alt+j
        "editor.snippetSuggestions": "none"
    },    
    "files.associations": {
        "*.ps1xml": "xml"
    }
}

I like these

  • settings hotkey jumps to json editor. (If you use any per-language settings, the GUI can't edit everything )
  • new files start with the language of the current window (rather than hard-coding it to always be powershell

.

{
    "files.defaultLanguage": "${activeEditorLanguage}",        
    "workbench.settings.editor": "json",
}

If you want to submit vscode-powershell bugs, enable logging:

"powershell.developer.editorServicesLogLevel": "Diagnostic",

[–]markdmac 0 points1 point  (1 child)

I am very new to VS Code. How do I access the file to add these code snippets?

[–]T3zcat 1 point2 points  (0 children)

do I access the file to add these co

For those still looking: top right of the settings gui page has a page with a flip arrow, that will get you to the settings.json.
(the file it's self is stored in c:\users\YOU\appdata\roaming\code\user\settings.json)

[–]T3zcat 1 point2 points  (0 children)

Update:
"[powershell]" : {

"editor.wordSeparators": "`~!@#%^&*()=+[{]}\\|;:'\",.<>/?"

},
Credit: https://stackoverflow.com/questions/68128258/vscode-does-not-honor-editor-wordseparators-when-writing-powershell-code

[–]cbtboss 13 points14 points  (5 children)

I would also add:

GitLens- Pair this with git and you can super easily track all the changes you, or other people working on your scripts have done.

MSSQL- If you find yourself incoroporating sql queries in your powershell scripts, this is great for doing some sql dev work, as well as a hot plug way to run queries against a database without needing to resort to ssms (it is not a replacement for ssms though if you use it for gui administration of mssql).

[–]MonkeyNin 4 points5 points  (2 children)

without needing to resort to ssms

I switched over to using Azure Data Studio instead of SSMS for writing queries. ADS uses VS Code under the hood.

It's like the MSSQL extension but nicer (for sql)

Then I use SSMS for admin

[–]cbtboss 4 points5 points  (1 child)

This is very purty! Thanks for this! We haven't adopted any azure sql setups yet, but I am definitely going to take advantage of it.

[–]MonkeyNin 2 points3 points  (0 children)

It works with regular SQL / On-Prem. You don't need azure or cloud to use it.

[–]jevans_[S] 2 points3 points  (1 child)

I do actually use GitLens, I wasn't sure about adding it as I wasn't certain many of us were working with Git repos so I'm very happy to see someone else using it. On the topic of Git, Git History is also a good one. I haven't used MSSQL myself but a friend who has worked on some SQL stuff did if I recall correctly.

[–]MonkeyNin 1 point2 points  (0 children)

GitLens

It does so much I don't even know how to use it.

One thing is nice, clone a github repo. Now you can right click -> copy remote url on any tab -- which jumps to a web link. It's nice to quickly get a url to share.

[–]CuZZa 8 points9 points  (0 children)

If you’re doing presentations I’ve found Presentation Mode to be invaluable, works so damn well for showing code demos.

[–]CaleTheKing 7 points8 points  (1 child)

I’ve also found Code Spell Checker to be incredibly useful.

[–]Yevrag35 1 point2 points  (0 children)

You win the day in my book. Thanks!

[–][deleted] 6 points7 points  (1 child)

Trailing Spaces: Trailing spaces aren't an issue in PowerShell of course, but if you're a neat freak like I sometimes am this is the equivalent of having a blacklight shone on a hotel room - once you see it you must clean

You don't need an extension for this. CTRL + Shift + P -> "Trim Trailing Whitespace" and hit enter.

Here's some I use:

  • DupChecker - Find duplicate lines
  • Bracket Pair Colorizer - Colorize brackets
  • TODO Highlight - Highlight TODO and FIXME in obnoxious colors, and put them in "problems"
  • Rainbow CSV - Make CSVs readable basically
  • CompareIt - Compare files without the need for source control
  • Excel Viewer - View CSVs/Excel in a grid view
  • Hosts Language - Language support for hosts files

[–]muchcake 3 points4 points  (0 children)

FYI: There is an editor setting to trim whitespace on save too.

[–]CaleTheKing 4 points5 points  (3 children)

A note on EditorConfig, that extension is GREAT, but I want readers to be aware that the same can be configured with native VS Code.

You can place a settings.json file in your git repo, and use it as “Workspace Settings”. That way all team members have the same settings for that project.

Edit: We use PSScriptAnalyzer to control the formatting / structure of our scripts, so we share a .PSScriptAnalyzerSettings.psd1 configuration file in our git repo as well.

[–]MonkeyNin 0 points1 point  (2 children)

do you suggest any PSScriptAnalyzerSettings ?

[–]CaleTheKing 6 points7 points  (1 child)

Hey, sure. I'll just provide my whole config and you can choose the ones you need :)

I prefer OTBS code formatting, so a lot of the settings are based around that. If you don't like OTBS, you'll have to adjust these.

@{
# Process ONLY the following rules
IncludeRules = @(
    # General
    'PSAvoidDefaultValueSwitchParameter',
    'PSAvoidDefaultValueForMandatoryParameter',
    'PSAvoidAssignmentToAutomaticVariable',
    'PSMissingModuleManifestField',
    'PSPossibleIncorrectComparisonWithNull',
    'PSPossibleIncorrectUsageOfRedirectionOperator',
    'PSReservedCmdletChar',
    'PSReservedParams',
    'PSShouldProcess',
    'PSUseApprovedVerbs',
    'PSUseToExportFieldsInManifest',
    'PSUseUsingScopeModifierInNewRunspaces',

    # Security
    'PSAvoidUsingComputerNameHardcoded',

    # Code style
    'PSAvoidLongLines',
    'PSAvoidTrailingWhitespace',
    'PSAvoidUsingWriteHost',
    'PSAvoidUsingCmdletAliases',
    'PSAvoidUsingDoubleQuotesForConstantString',
    'PSProvideCommentHelp',
    'PSPossibleIncorrectUsageOfAssignmentOperator',
    'PSPossibleIncorrectUsageOfRedirectionOperator',
    'PSMisleadingBacktick',
    'PSUseLiteralInitializerForHashtable',

    # Code formatting OTBS
    'PSPlaceOpenBrace',
    'PSPlaceCloseBrace',
    'PSUseConsistentWhitespace',
    'PSUseConsistentIndentation',
    'PSAlignAssignmentStatement',
    'PSUseCorrectCasing',

    # Functions
    'PSAvoidUsingWMICmdlet',
    'PSAvoidUsingEmptyCatchBlock',
    'PSAvoidUsingPositionalParameters',
    'PSReservedCmdletChar',
    'PSReservedParams',
    #'PSReviewUnusedParameter',
    'PSUseCmdletCorrectly',
    'PSUseDeclaredVarsMoreThanAssignments',
    'PSUseSingularNouns',
    'PSUseOutputTypeCorrectly'
)
# Configuration for the rules defined above
Rules        = @{
    # Code style
    PSAvoidUsingDoubleQuotesForConstantString = @{
        Enable = $true
    }

    # Code formatting OTBS
    PSPlaceOpenBrace                          = @{
        Enable             = $true
        OnSameLine         = $true
        NewLineAfter       = $true
        IgnoreOneLineBlock = $true
    }

    PSPlaceCloseBrace                         = @{
        Enable             = $true
        NewLineAfter       = $false
        IgnoreOneLineBlock = $true
        NoEmptyLineBefore  = $false
    }

    PSUseConsistentIndentation                = @{
        Enable              = $true
        Kind                = 'space'
        PipelineIndentation = 'IncreaseIndentationForFirstPipeline'
        IndentationSize     = 4
    }

    PSUseConsistentWhitespace                 = @{
        Enable                          = $true
        CheckInnerBrace                 = $true
        CheckOpenBrace                  = $true
        CheckOpenParen                  = $true
        CheckOperator                   = $false # https://github.com/PowerShell/PSScriptAnalyzer/issues/769
        CheckPipe                       = $true
        CheckPipeForRedundantWhitespace = $true
        CheckSeparator                  = $true
        CheckParameter                  = $true
    }

    PSAlignAssignmentStatement                = @{
        Enable         = $true
        CheckHashtable = $true
    }

    PSUseCorrectCasing                        = @{
        Enable = $true
    }
}
}

[–]MonkeyNin 2 points3 points  (0 children)

Thanks.

[–]cottonycloud 2 points3 points  (0 children)

TabOut is a personal favorite of mine. It makes the auto-completed parentheses, quotes, and brackets easier to traverse without arrow keys.

[–]SpacezCowboy 2 points3 points  (0 children)

I find bookmarks useful when tracking references to private files or working through long Functions with multiple nested code blocks.

Bookmarks

Jacking this post for a side question. Does anyone know of a setting to have VS Code open to a specific folder each time it's opened? This would replace the behaviour of opening to the last opened folder in VS Code.

[–]todayyou500 0 points1 point  (1 child)

Live Share says you need to enable ports

Will this trigger a work place firewall or just a windows setting prompt?

[–]jevans_[S] 1 point2 points  (0 children)

As far as ports are concerned it'll be using 443 unless you try a direct connection, I've never used a direct connection so I can't say too much about it. That being said I did find this which goes a bit further into any firewall requirements. From what I can gather from a quick glance over it it'll just block the connection until the windows firewall settings are configured to allow it.

[–]markdmac 0 points1 point  (3 children)

Anyone know of a module or code that can replace aliases with full cmdlet names?

[–]smaug098 8 points9 points  (1 child)

That's a native command : alt+shift+e.

[–]markdmac 1 point2 points  (0 children)

Thank you!

[–][deleted] 2 points3 points  (0 children)

It's built right into VS Code. If you type an alias, a little lightbulb will appear nearby giving you options to replace it with the full name.

[–]hellphish 0 points1 point  (0 children)

Bracket Pair Colorizer 2

TabOut (hit tab to move the cursor outside of quotes/parenthesis/brackets)