Categories
App Config Getting-Started PowerShell VS Code

Viewing Default Settings in VS Code

Where is the default settings.json or keybindings.json ? There isn’t one, because it’s dynamically generated.

When you run run the ‘default settings’ command, it builds a new one — this means it’s always up to date. It includes settings from all enabled addons.

Command Palette: The Only Hotkey You Need to Remember.

Can’t remember what key formats without saving? No problem, f1 -> forsave and it will come up.

Go to Symbol: The Secret to Navigating giant JSON files

It’s better than using a regular search ctrl+f . If you searched for ‘fontsize’ not only will you get every setting, but, lots of comments as well. When there’s duplicate settings, the bottom one has priority. If you like customizing, you may end up with duplicated keys. This instantly lets shows you which is the final one. Even if they are 3000 lines apart.

Control+Space: The 2nd Best Hotkey

As you’re editing, ctrl+space will fuzzy search every possible setting. Hit it a 2nd time to toggle the documentation.

Searching Keybindings by Name or Command by name

Suggested PowerShell Config

I tried keeping it short, I recommend checking these settings for PowerShell.
If you want to control autocomplete or suggestions , this config has notes on some properties to check out.

{
    // this file is almost the same as 
    //<https://github.com/ninmonkey/dotfiles_git/blob/614fc06cd8b989e8438cba6cae648605fae2491a/vscode/User/nin10/Code/minimum-config/powershell.settings.json>

    "workbench.settings.editor": "json", // good for editing, [ctrl+,]
    // will by default open your global settings as JSON instead of UI

    // improve code quality
    "powershell.codeFormatting.autoCorrectAliases": true,
    "powershell.codeFormatting.useConstantStrings": true,
    "powershell.codeFormatting.useCorrectCasing": true,

    // I have this enabled for most languages
    "editor.formatOnSave": true,

    // some people are pretty polarized on which style to use, 
    // So I have both styles and variants to try
    "editor.wordSeparators": "`~!@#%^&*()=+[{]}\\|;:'\",.<>/?", // combine $ and -
    "editor.wordSeparators": "`~!@#%^&*()-=+[{]}\\|;:'\",.<>/?", // causes splat-expression etc to break
    "editor.wordSeparators": "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?", // break on $ and -
    "editor.wordSeparators": "`~!@#%^&*()=+[{]}\\|;:'\",.<>/?", // combine $ and -
    "editor.wordSeparators": "`~!@#%^&*()-=+[{]}\\|;:'\",.<>/?",

    // If you don't like snippets, you can disable them for as specific language, leaving the others
    // the blog isn't rendering the next line, it should say
    // "[power shell]" as the key If you don't like snippets, you can disable them for as specific language, leaving the others
    "[powershell]": {
        "editor.semanticHighlighting.enabled": false,
        "editor.snippetSuggestions": "bottom",
        "editor.snippetSuggestions": "none",
        "files.encoding": "utf8bom",
        "files.trimTrailingWhitespace": true,
    },

    /*
        Adds autocompletion and validation to any .Format.ps1xml and .Types.ps1xml files.
        It uses the addon: 'redhat.vscode-xml'
    */
    "editor.suggest.preview": true, // interesting but can be jarring   
    ],

    "powershell.integratedConsole.suppressStartupBanner": true,
    "powershell.powerShellDefaultVersion": "PowerShell (x64)",

    "powershell.promptToUpdatePowerShell": false,
    // Specifies the path to a PowerShell Script Analyzer settings file. To override the default settings for all projects, enter an absolute path, or enter a path relative to your workspace.
    "powershell.scriptAnalysis.settingsPath": "C:/Users/monkey/Documents/2021/dotfiles_git/powershell/PSScriptAnalyzerSettings.psd1",
    // "powershell.scriptAnalysis.settingsPath

     // Autocomplete and a schema/validation for
     // powershell's  "types.ps1xml" and "format.ps1xml" files
     "xml.fileAssociations": [
        {
            "systemId": "https://raw.githubusercontent.com/PowerShell/PowerShell/master/src/Schemas/Format.xsd",
            "pattern": "**/*.Format.ps1xml"
        },
        {
            "systemId": "https://raw.githubusercontent.com/PowerShell/PowerShell/master/src/Schemas/Types.xsd",
            "pattern": "**/*.Types.ps1xml"
        }

}

Error Lens

"errorLens.followCursor": "closestProblem",
"errorLens.followCursorMore": 2,

One of the extensions from Justin Grote’s addon pack is the error lens. I like it, after reducing the visual noise. You can

See More:

For customizing themes, check out these settings. There’s different sections depending on if semantic color is enabled

"editor.semanticTokenColorCustomizations": { ... },
"editor.tokenColorCustomizations": { ... },

https://cdn.discordapp.com/attachments/447579065877266454/969757374216802304/unknown.png
Categories
Experiment PowerShell Pwsh7+

Experiments of 2022-04

FdFind, Ansi Colors with Group-Object

# [3] main + UX for long exxtensions + Horizontal rules
fd --color=always --changed-within=10hours
| group { 
    $strExt = $_ | StripAnsi | gi | % Extension
    # QOL: don't let massive names break the table
    if($strExt.Length -gt 10) { $strExt.Substring(0, 10) } else {$strExt}
}
| %{ $_ ; hr }
| ft -AutoSize
# [1] Minimum required
fd --color=always --changed-within=10hours
| group { $_ | StripAnsi | gi | % Extension }
| ft -AutoSize
# [2] UX: Don't let super long extensions break break columns
fd --color=always --changed-within=10hours
| group {
    $strExt = $_ | StripAnsi | gi | % Extension
    if($strExt.Length -gt 10) { $strExt.Substring(0, 10) } else {$strExt}
}
| ft -AutoSize

Using wt‘s Parameters

https://github.com/Ninmonkey.Console/WtThemeTest
PS> ZD-Invoke-WtThemeTest -Random
PS> wt -w theme-test new-tab --title "Tango Light" --profile 'pwsh_nop' --colorScheme "Tango Dark"
PS> wt -w theme-test new-tab --title "Tango Light" --profile 'pwsh_nop' --colorScheme "BirdsOfParadise"

# or
ZD-Invoke-WtThemeTest -Random

Nested Formatting in Powershell

Using module Pansies
What not to do 🙂

CLI bat to preview results

# For every file fd finds, print the first 15 lines
PS> fd --exec-batch bat --line-range=:15 --paging=always

# forcing paging /on/off
PS> fd --exec-batch bat --line-range=:15 --paging=never

Regex Lazy vs Greedy Expressions

Using CSS Selectors

selector 'div.premium-box span.btn.btn-info'

Autocomplete changes based on the first Argument

Parsing Stdout Whitespace

Grouping On Errors

Type Resolution Is Scoped

Pwsh🐒> # test whether it's resolved by coerce to [type]
    'catman' -as 'type' -is 'type'
    'batman' -as 'type' -is 'type'
True
False
Pwsh🐒> # test whether it's resolved by coerce to [type]
    'catman' -as 'type' -is 'type'
    'batman' -as 'type' -is 'type'
True
False


# after 

Pwsh🐒> @(
    # Declaring a new type in inside a [ScriptBlock]
    & {
        class batman { [string]$Name }
        [batman]
    }

    # verses dotsourcing a type into the current scope
    . {
       class catman { [string]$Name }
       [catman]
    }) | ft -AutoSize

   Namespace: <4cf9efd5>

Access Modifiers Name   BaseType
------ --------- ----   --------
public class     batman object

   Namespace: <f2200555>

Access Modifiers Name   BaseType
------ --------- ----   --------
public class     catman object
Categories
Cheatsheet Command Line Excel Power BI Power Query PowerShell

Big List of Cheat sheets and References

Web

XPath

OData

HTTP

Other: Web

Encoding

Unicode.org

Emoji

Table of Contents: Emoji Charts Table

Apps

VS Code

Firefox

Windows Terminal

Excel

Other: Apps

  • .

git

Misc

Programming and Languages

PowerShell

gist/vexx32/PowershellLoopBehavior.md

Power Query

Dotnet / .Net

Linux

Bash

Environment Vars

Categories
PowerShell Quick Tips

Creating a Discord Webhook in a few lines of PowerShell

Discord Web Hooks are easier than you’d think. It uses a regular `HTTP` web request .

Step1: Creating your webhook url

Go to: Server Settings -> Integrations -> View Webhooks
Then click create webhook.

Choose a name, the channel, then copy webhook url

Step2: Invoke-RestMethod

$webhookUri = 'https://discord.com/api/YourWebhookUrlHere'

$Body = @{
  'username' = 'Nomad'
  'content' = 'https://memory-alpha.fandom.com/wiki/Nomad'
}
Invoke-RestMethod -Uri $webhookUri -Method 'post' -Body $Body

Success!

Docs

There are optional webhook arguments to customize the output: https://discord.com/developers/docs/resources/webhook#execute-webhook

Comparison with curl

I tried making curl easier to read by splitting content, and pipe so that you don’t have to manually escape Json

$Json = @{ 'username' = 'Nomad'; 'content' = 'https://memory-alpha.fandom.com/wiki/Nomad' } | ConvertTo-Json -Compress

$Json | curl -X POST -H 'Content-Type: application/json' -d '@-' $webhookUri

Categories
Command Line PowerShell Quick Tips References And Cheat Sheets

Easy way to cache results on the Command Line | Power Shell Tip

Sometimes you’ll need to run a command with the same input with different logic.
This can be a hassle using a slow command like Get-ADUser or Get-ChildItem on a lot of files like ~ (Home) with -Depth / -Recurse

ls ~ -Depth 4 | Format-Table Name

PowerShell 7.0+

Powershell 7 added the Ternary Operator, and several operators for handling $null values.

All of these examples will only run Get-ChildItem the first time. Any future calls are cached.

Null-Coalesce ??= Assignment Operator

This is my favorite on the Command line. The RHS (Right Hand Side) skips evaluation if the left side is not $null

$AllFiles ??= ls ~ -Depth 4

Using the Null-Coalesce ?? Operator

$AllFiles = $AllFiles ?? ( ls ~ -Depth 4  )

Ternary Operator ? whenTrue : WhenFalse

$allFiles = $allFiles ? $allFiles : ( ls ~ -Depth 4 )

Windows PowerShell and Powershell < 7

Windows Powershell can achieve the same effect with an if statement

if(! $AllFiles) { $AllFiles = ls ~ -Depth 4 }
Categories
Command Line Getting-Started PowerShell Pwsh7+ Quick Tips What's New

PowerShell : Prefixing lines with the Pipe operator |

There’s a lot of ways to use line continuations in Windows Powershell without backticks . Powershell added a new one, the | pipe operator. It’s cleaner to read, and makes it easier to insert, delete, or toggle comments on the console.

Now you can write:

# Powershell
ls | sort Length
| Select -First 10
| ft Name, Length

Instead of piping on line endings

# Windows Powershell
ls | sort Length |
Select -First 10 |
ft Name, Length

# or
ls | sort Length | Select -First 10 | ft Name, Length
Categories
Formatting PowerShell Snippets

Reusable Calculated Properties in PowerShell

The function Label is from the module: github.com/Ninmonkey.Console

$basePath = 'C:\Program Files'
$calcProp = @{}
$calcProp.FileSize = @{
    n         = 'Size'
    e         = { $_.Length | Format-FileSize }
    Alignment = 'right'
}
# relative path defaults to relative your current location, so I override it
$calcProp.RelativePath = @{
    n = 'RelativePath'
    e = {
        Push-Location $baseBath
        $_.FullName | Resolve-Path -Relative
        Pop-Location
    }
}
$calcProp.ColorizedName = @{
    n = 'ColorName'
    e = {
        $Color = ($_ | Test-IsDirectory) ? 'blue' : 'green'
        Label $_.Name -fg $Color -Separator ''
    }
}

$DefaultPropList = 'Name', $calcProp.ColorizedName, $calcProp.RelativePath

Label 'basePath' $basePath

$files = Get-ChildItem $basePath -Depth 2
$files | Format-Table Name, Length, $calcProp.FileSize, $calcProp.RelativePath

$files | Format-Table  $calcProp.FileSize, $calcProp.ColorizedName

# Using pre-declared property lists, which may include scriptblocks like $calcProp.FileSize
$files | Format-Table -Property $DefaultPropList

Categories
PowerShell References And Cheat Sheets

Learning PowerShell

Getting started with PowerShell

Main

Grammar

Important Topics, Language quirks

For( ;; ) vs ForEach vs ForEach-Object

It’s first argument is a ScriptBlock so it appears like a control loop.

Notice return verses break in ForEach-Object . Remember that the { ... stuff ... } in this case is an anonymous function , not a language control statement
It is a parameter to the ForEach-Object . When not specified, it’s the -Process Parameter

Flow Control with language Keywords

Attributes for validation

Best Practices

Naming

Categories
PowerShell Quick Tips Regex

Using Case-Sensitive Regular expressions in PowerShell – Tips

Say you want to find functions that uses parameters named like:
-AsString, -AsHashTable, or -AsByteStream

Using Find-Member makes it easy.

> Find-Member -Name 'As*'

That’s close, but I want it to start with a capital letter, to skip matches like:
Assembly or Asin

Converting Like to a Regex

The -like pattern As* is the same as the regex ^As
To start with a capital letter you could use: ^As[A-Z]

Disabling Case-Sensitive matches

Because PowerShell defaults to case-insensitive matches
You need to remove the i insensitive flag using the syntax (?-i)

Solution

> Find-Member -Name '(?-i)^As[A-Z]' -RegularExpression

The final pattern is (?-i)^As[A-Z]
Making it case-sensitive narrowed down the matches from 113 to 43 !

See More