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