Aller au contenu

Powershell 7 configuration

De Banane Atomic

Links

Useful commands

# reload profile
. $PROFILE

# get the current powershell version
$PSVersionTable.PSVersion

Profiles

Profiles are loaded in the following order :

Current user and PS terminal $profile
$profile.CurrentUserCurrentHost
$home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Current user and all termnals $profile.CurrentUserAllHosts $home\Documents\PowerShell\profile.ps1
All users and PS terminal $profile.AllUsersCurrentHost C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1
All users and all terminals $profile.AllUsersAllHosts C:\Program Files\PowerShell\7\profile.ps1
# create a new profile (file and folder)
new-item -path $profile -itemtype file -force
# -force to overwrite an existing one
$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# include other files
. $home\Documents\PowerShell\Alias.ps1
. $home\Documents\PowerShell\Function.ps1
Alias.ps1
New-Alias e 'C:\WINDOWS\explorer.exe'
Function.ps1
function .. { Set-Location .. }
function ... { Set-Location ..\.. }
function which($name) {
    Get-Command $name | Select-Object -ExpandProperty Definition
}

Modules

PowerShell Gallery

# search for a module
Find-Module <ModuleName>

# install / uninstall a module
Install-Module -Name <ModuleName> -Scope CurrentUser
Uninstall-Module -Name <ModuleName>
# force uninstallation of all versions
Uninstall-Module <ModuleName> -AllVersions -Force

# list loaded modules
Get-Module
# list installed modules
Get-Module -ListAvailable

# load / unload a module
Import-Module <ModuleName>
Remove-Module <ModuleName>
$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Import-Module <ModuleName>
# modules installation paths
$env:PSModulePath -split [System.IO.Path]::PathSeparator
# %HomePath%\Documents\PowerShell\Modules
# C:\Program Files\PowerShell\Modules

PSReadLine

PSReadLine 2.3+ est déjà installé et importé.
$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
# searching for commands in history with up/down arrow
Set-PSReadLineKeyHandler -Key UpArrow   -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

# move the cursor to the end after history search
Set-PSReadLineOption -HistorySearchCursorMovesToEnd

# inline prediction
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle InlineView
# get the current PSReadLine version
(Get-Module PSReadLine).Version

SamplePSReadLineProfile.ps1

↑ ↓ Browse the history
F7 Show command history
Alt + W Save current line in history but do not execute
Alt + ( Put parenthesis around the selection or entire line and move the cursor to after the closing parenthesis
Alt + ' Toggle quotes on the argument under the cursor
Alt + % Replace all aliases with the full command

Warp Directory

$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Import-Module Warp-Directory
# name the current path as a new warp point
wda [name]

# remove a warp point
wdrm [name]

# list the warp point
wdls
$env:USERPROFILE\Documents\PowerShell\Modules\Warp-Directory\Warp-Directory.psd1
@{
    RootModule        = 'Warp-Directory.psm1'
    ModuleVersion     = '1.0.0'
    GUID              = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'
    Author            = ''
    Description       = 'Warp Directory - Raccourcis de navigation rapide dans le terminal'
    PowerShellVersion = '7.0'
    FunctionsToExport = @('Set-WarpPoint', 'Remove-WarpPoint', 'Get-WarpPoint', 'Invoke-WarpPoint', 'Clear-WarpPoints')
    AliasesToExport   = @('wd', 'wda', 'wdrm', 'wdls', 'wdclean')
}
$env:USERPROFILE\Documents\PowerShell\Modules\wd\wd.psm1
# ============================================================
# Configuration
# ============================================================
$script:WarpFile = Join-Path $HOME '.warppoints.json'

# ============================================================
# Fonctions internes
# ============================================================
function Load-WarpPoints {
    if (Test-Path $script:WarpFile) {
        $content = Get-Content $script:WarpFile -Raw
        if ($content) {
            return $content | ConvertFrom-Json -AsHashtable
        }
    }
    return @{}
}

function Save-WarpPoints {
    param([hashtable]$Points)
    $Points | ConvertTo-Json -Depth 1 | Set-Content $script:WarpFile -Encoding UTF8
}

# ============================================================
# Complétion dynamique (Tab)
# ============================================================
$script:WarpCompleter = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
    $points = Load-WarpPoints
    $points.Keys | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new(
            $_,
            $_,
            'ParameterValue',
            "→ $($points[$_])"
        )
    }
}

# ============================================================
# Fonctions publiques
# ============================================================

function Set-WarpPoint {
    <#
    .SYNOPSIS
        Enregistre un warp point pour le répertoire courant.
    .EXAMPLE
        wda projet
    .EXAMPLE
        wda docs C:\Users\Moi\Documents
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Name,

        [Parameter(Position = 1)]
        [string]$Path
    )

    $points = Load-WarpPoints

    if (-not $Path) {
        $Path = (Get-Location).Path
    }

    if (-not (Test-Path $Path)) {
        Write-Host "  ✗ Le chemin '$Path' n'existe pas." -ForegroundColor Red
        return
    }

    $Path = (Resolve-Path $Path).Path

    if ($points.ContainsKey($Name)) {
        Write-Host "  ⚠ Warp point '$Name' mis à jour." -ForegroundColor Yellow
    }
    else {
        Write-Host "  ✓ Warp point '$Name' créé." -ForegroundColor Green
    }

    $points[$Name] = $Path
    Save-WarpPoints $points
    Write-Host "    → $Path" -ForegroundColor DarkGray
}

function Remove-WarpPoint {
    <#
    .SYNOPSIS
        Supprime un warp point.
    .EXAMPLE
        wdrm projet
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Name
    )

    $points = Load-WarpPoints

    if ($points.ContainsKey($Name)) {
        $path = $points[$Name]
        $points.Remove($Name)
        Save-WarpPoints $points
        Write-Host "  ✓ Warp point '$Name' supprimé." -ForegroundColor Green
        Write-Host "    ✗ $path" -ForegroundColor DarkGray
    }
    else {
        Write-Host "  ✗ Warp point '$Name' introuvable." -ForegroundColor Red
        Write-Host ""
        Write-Host "  Points disponibles :" -ForegroundColor Yellow
        Get-WarpPoint
    }
}

function Get-WarpPoint {
    <#
    .SYNOPSIS
        Liste tous les warp points enregistrés.
    .EXAMPLE
        wdls
    #>
    [CmdletBinding()]
    param()

    $points = Load-WarpPoints

    if ($points.Count -eq 0) {
        Write-Host "  Aucun warp point enregistré." -ForegroundColor DarkGray
        Write-Host "  Utilise 'wda <nom>' pour en créer un." -ForegroundColor DarkGray
        return
    }

    Write-Host ""
    Write-Host "  📍 Warp Points" -ForegroundColor Cyan
    Write-Host "  ─────────────────────────────────────────" -ForegroundColor DarkGray

    $maxLen = ($points.Keys | Measure-Object -Maximum -Property Length).Maximum

    $points.GetEnumerator() | Sort-Object Key | ForEach-Object {
        $name = $_.Key.PadRight($maxLen)
        $path = $_.Value
        $exists = Test-Path $path

        if ($exists) {
            Write-Host "    " -NoNewline
            Write-Host "$name" -ForegroundColor Green -NoNewline
            Write-Host "  →  " -ForegroundColor DarkGray -NoNewline
            Write-Host "$path" -ForegroundColor White
        }
        else {
            Write-Host "    " -NoNewline
            Write-Host "$name" -ForegroundColor Red -NoNewline
            Write-Host "  →  " -ForegroundColor DarkGray -NoNewline
            Write-Host "$path (introuvable!)" -ForegroundColor Red
        }
    }

    Write-Host ""
}

function Invoke-WarpPoint {
    <#
    .SYNOPSIS
        Navigue vers un warp point.
    .EXAMPLE
        wd projet
    .EXAMPLE
        wd projet src
    #>
    [CmdletBinding()]
    param(
        [Parameter(Position = 0)]
        [string]$Name,

        [Parameter(Position = 1, ValueFromRemainingArguments)]
        [string[]]$SubPath
    )

    if (-not $Name) {
        Get-WarpPoint
        return
    }

    $points = Load-WarpPoints

    if (-not $points.ContainsKey($Name)) {
        Write-Host "  ✗ Warp point '$Name' introuvable." -ForegroundColor Red
        Write-Host ""

        $suggestions = $points.Keys | Where-Object {
            ($_ -like "*$Name*") -or ($Name -like "*$_*")
        }

        if ($suggestions) {
            Write-Host "  Peut-être :" -ForegroundColor Yellow
            $suggestions | ForEach-Object {
                Write-Host "    → $_" -ForegroundColor Cyan
            }
        }
        else {
            Write-Host "  Utilise 'wdls' pour voir les points disponibles." -ForegroundColor DarkGray
        }
        return
    }

    $targetPath = $points[$Name]

    if ($SubPath) {
        $targetPath = Join-Path $targetPath ($SubPath -join '\')
    }

    if (Test-Path $targetPath) {
        Set-Location $targetPath
        Write-Host "  → $targetPath" -ForegroundColor DarkGray
    }
    else {
        Write-Host "  ✗ Le chemin '$targetPath' n'existe plus." -ForegroundColor Red
        Write-Host "  Supprime-le avec : wdrm $Name" -ForegroundColor DarkGray
    }
}

function Clear-WarpPoints {
    <#
    .SYNOPSIS
        Supprime tous les warp points dont le chemin n'existe plus.
    .EXAMPLE
        wdclean
    #>
    [CmdletBinding()]
    param()

    $points = Load-WarpPoints
    $removed = 0

    Write-Host ""
    Write-Host "  🧹 Nettoyage des warp points..." -ForegroundColor Cyan
    Write-Host ""

    $toRemove = @()
    foreach ($key in $points.Keys) {
        if (-not (Test-Path $points[$key])) {
            Write-Host "    ✗ $key → $($points[$key])" -ForegroundColor Red
            $toRemove += $key
            $removed++
        }
    }

    foreach ($key in $toRemove) {
        $points.Remove($key)
    }

    if ($removed -gt 0) {
        Save-WarpPoints $points
        Write-Host ""
        Write-Host "  $removed point(s) supprimé(s)." -ForegroundColor Green
    }
    else {
        Write-Host "  Tout est propre ! ✓" -ForegroundColor Green
    }
    Write-Host ""
}

# ============================================================
# Alias
# ============================================================
New-Alias -Name wd       -Value Invoke-WarpPoint   -Force -Scope Global
New-Alias -Name wda      -Value Set-WarpPoint      -Force -Scope Global
New-Alias -Name wdrm     -Value Remove-WarpPoint   -Force -Scope Global
New-Alias -Name wdls     -Value Get-WarpPoint      -Force -Scope Global
New-Alias -Name wdclean  -Value Clear-WarpPoints   -Force -Scope Global

# ============================================================
# Complétion Tab
# ============================================================
Register-ArgumentCompleter -CommandName 'Invoke-WarpPoint' -ParameterName 'Name' -ScriptBlock $script:WarpCompleter
Register-ArgumentCompleter -CommandName 'Remove-WarpPoint' -ParameterName 'Name' -ScriptBlock $script:WarpCompleter
Register-ArgumentCompleter -CommandName 'wd'   -Native -ScriptBlock $script:WarpCompleter
Register-ArgumentCompleter -CommandName 'wdrm' -Native -ScriptBlock $script:WarpCompleter

# Message de chargement
$pointCount = (Load-WarpPoints).Count
Write-Host "  📍 Warp-Directory chargé ($pointCount warp points)" -ForegroundColor DarkGray

External tools

eza

  • Manual installation:
    • get the download url from the scoop installer [1]
    • download and extract into $home\AppData\Local\eza
    • add it to the user PATH
$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
function l { eza --icons --group-directories-first @args }
function la { eza -a --icons --group-directories-first @args }
function eza-ls { eza -l --icons --group-directories-last @args }
Set-Alias ls eza-ls
function lsa { eza -la --icons --group-directories-first @args }
function lt { eza --tree --icons --level=2 @args }

Errors

Error updating shortcut

Unable to modify the terminal.
Copy the shortcut to the local user start menu:

  • C:\ProgramData\Microsoft\Windows\Start Menu\Programs\PowerShell\PowerShell 7 (x64).lnk
  • $home\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\PowerShell\PowerShell 7 (x64).lnk

Then pin the local user shortcut.

Installation

winget install Microsoft.PowerShell

# check the installed version
$PSVersionTable.PSVersion

# installed here
C:\Program Files\WindowsApps\Microsoft.PowerShell_7.3.1.0_x64__8wekyb3d8bbwe\pwsh.exe