Powershell configuration

De Banane Atomic
Aller à la navigationAller à la recherche

Liens

Modules

PowerShell Gallery

Powershell.svg
# liste les modules chargés
Get-Module

# charger un module
Import-Module <ModuleName>
Remove-Module <ModuleName>

# liste les modules disponibles
Get-Module -ListAvailable

# Installer un module dans une console ouverte en mode administrateur
Install-Module -Name <ModuleName>
Uninstall-Module -Name <ModuleName>
Find-Module <ModuleName>
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Import-Module <ModuleName>
PSColor Provides basic color highlighting for files, services, select-string etc.
Get-ChildItemColor provides colored version of Get-ChildItem Cmdlet
posh-git provides prompt with Git status summary information and tab completion for Git commands, parameters, remotes and branch names
PowerShell Beautifier format powershell code
Ps.svg
echo $env:PSModulePath
# %ProgramFiles%\WindowsPowerShell\Modules
# %HomePath%\Documents\WindowsPowerShell\Modules

PSReadLine

PSReadLine 2.0 est déjà installé et importé.
Ps.svg
# Searching for commands with up/down arrow is really handy.  The
# option "moves to end" is useful if you want the cursor at the end
# of the line while cycling through history like it does w/o searching,
# without that option, the cursor will remain at the position it was
# when you used up arrow, which can be useful if you forget the exact
# string you started the search on.
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

SamplePSReadLineProfile.ps1

↑ ↓ Naviguer dans l'historique
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

Bash tools

fd (bash)

Ps.svg
choco install fd

ripgrep (bash)

Ps.svg
choco install ripgrep

gsudo

Ps.svg
choco install gsudo

# elevate the current shell in the current console window (Cmd/PowerShell/Pwsh Core/Yori)
sudo

# launch the current shell elevated in a new console window
sudo -n

# command
sudo md "C:\Windows\Test"

# Enable credentials cache (less UAC popups)
sudo config CacheMode Auto

Warp Directory (bash)

Télécharger PoShWarp.psm1 et le copier dans WindowsPowerShell\Modules\PoShWarp
Le module sera importer automatiquement au démarrage de powershell.

Désactiver le beep

Powershell.svg
Set-PSReadlineOption -BellStyle None

Connaitre la version de PowerShell installée

Powershell.svg
$PSVersionTable.PSVersion
 
Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

Associer les fichiers *.ps1 à PowerShell

Par défaut, les fichiers *.ps1 sont associés à Notepad.

Associer les fichiers *.ps1 avec HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell
PowerShell (Default) = 0
Notepad (Default) = Open
PowerShell ISE (Default) = Edit

Ouvrir un terminal PowerShell depuis Explorer

Shift + clique droit → Open PowerShell window here
Sinon créer sa propre entrée dans le menu contextuel d'Explorer:
regeditComputer\HKEY_CLASSES_ROOT\Directory\Background\shell Il suffirait de supprimer la String-Value Extended du dossier Powershell pour rendre l'entrée Open PowerShell window here accessible sans avoir à appuyer sur Shift.
Mais comme ce n'est pas possible, on peut créer une nouvelle entrée:

  1. New KeyPowerShell2
    1. (Default) = @shell32.dll,-8508
    2. New String ValueNoWorkingDirectory
    3. New String ValueIcon = C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    4. New DWORD (32-bit) ValueShowBasedOnVelocityId = 639bc8 (Hexadecimal)
    5. New Keycommand
      1. (Default) = powershell.exe -noexit -command Set-Location -literalPath '%V'

Inclure des fichiers

Powershell.svg
# dot sourcing
. C:\chemin\vers\fichier.ps1

. (join-path -path $PSScriptRoot -childpath "fichier.ps1")
$PSScriptRoot permet d'obtenir le chemin vers le script courant.

Exécuter du code avec le privilège Administrateur

Powershell.svg
$code = "start-service 'my_service' -PassThru"
Start-Process -FilePath powershell.exe -ArgumentList $code -verb RunAs -WorkingDirectory C:

A self elevating PowerShell script

Powershell.svg
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
	# We are running "as Administrator" - so change the title and background color to indicate this
	$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
	$Host.UI.RawUI.BackgroundColor = "DarkBlue"
	clear-host
}
else
{
	# We are not running "as Administrator" - so relaunch as administrator

	# Create a new process object that starts PowerShell
	$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

	# Specify the current script path and name as a parameter
	$newProcess.Arguments = $myInvocation.MyCommand.Definition;

	# Indicate that the process should be elevated
	$newProcess.Verb = "runas";

	# Start the new process
	[System.Diagnostics.Process]::Start($newProcess);

	# Exit from the current, unelevated, process
	exit
}

# Code à exécuter avec les droits UAC

# Permet de garder la console ouverte
Write-Host -NoNewLine "`nPress any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Visual Studio avec PowerShell Tools

Extension « PowerShell Tools for Visual Studio 2013 » à installer pour pouvoir éditer les fichiers PowerShell dans Visual Studio.

Completion - PowerTab

Désarchiver le module dans « Mes Documents\WindowsPowerShell\Modules »

Powershell.svg
# installation du module
Import-Module PowerTab
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# importer le module au lancement de PowerShell
Import-Module "PowerTab" -ArgumentList "C:\Users\Nicolas\Documents\WindowsPowerShell\PowerTabConfig.xml"

Get-Content : Cannot find path 'Function:\TabExpansion' because it does not exist

%UserProfile%\My Documents\WindowsPowerShell\Modules\PowerTab\TabExpansion.ps1
# ligne 17 remplacer « TabExpansion » par « TabExpansion2 »
$OldTabExpansion = Get-Content Function:TabExpansion2

Alias

Les alias servent juste à lier une commande à un exécutable ou à une autre commande.
Pour lier une commande à du code utiliser plutôt une fonction.
Powershell.svg
# liste des alias
get-alias
gal

# connaitre la valeur d'un alias
alias <mon-alias>

# créé l'alias np pour Notepad++
New-Alias np "C:\Program Files\Notepad++\notepad++.exe"
Pour rendre les alias permanents il faut les ajouter au profil.
Set-Alias pour modifier un alias, New-Alias pour créer un nouvel alias, créé une erreur en cas de doublon.

Cannot resolve alias 'xxx' because it refers to term 'yyy'

Cannot resolve alias 'xxx' because it refers to term 'yyy', which is not recognized as a cmdlet, function, operable program, or script file
Utiliser une fonction plutôt qu'un alias.

Alias is not writeable because alias xxx is read-only or constant and cannot be written to

Powershell.svg
# supprimer l'alias built-in const / read-only
del alias:gc -Force
Set-Alias gc git-commit

Profils

Les profils sont chargé au lancement de la console PS et éxécuté dans l'ordre suivant :

Uniquement pour l'utilisateur actuel et pour la console PS $profile
$profile.CurrentUserCurrentHost
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Uniquement pour l'utilisateur actuel et tous les interpréteurs de commandes $profile.CurrentUserAllHosts %UserProfile%\Documents\WindowsPowerShell\profile.ps1
Pour tous les utilisateurs mais uniquement pour la console PS $profile.AllUsersCurrentHost %windir%\system32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1
Pour tous les utilisateurs et tous les interpréteurs de commandes $profile.AllUsersAllHosts %windir%\system32\WindowsPowerShell\v1.0\profile.ps1
Powershell.svg
# commande de création du profil : création du dossier et du fichier
new-item -path $profile -itemtype file -force
# l'option force permet d'écraser le profil s'il existait déjà

echo $profile
# $home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# include other files
. $home\Documents\WindowsPowerShell\Alias.ps1
. $home\Documents\WindowsPowerShell\Function.ps1
Alias.ps1
New-Alias l 'Get-ChildItem'
New-Alias e 'C:\WINDOWS\explorer.exe'
New-Alias np 'C:\Program Files\Notepad++\notepad++.exe'

New-Alias aaa "$home\Documents\Scripts\MyScript.ps1"
Function.ps1
function f1 {
    "$home\Documents\Scripts\MyScript.ps1" @args
}

function f2 {
    & "$Env:Programfiles\Mozilla Firefox\firefox.exe" -P 'MyProfile' -no-remote
}
Splatting @args
Ps.svg
# reload profile
.$profile

Customizing the Windows PowerShell Console

(Get-Host).UI.RawUI
ForegroundColor       : DarkYellow
BackgroundColor       : DarkMagenta
CursorPosition        : 0,4
WindowPosition        : 0,0
CursorSize            : 25
BufferSize            : 120,3000
WindowSize            : 120,50
MaxWindowSize         : 120,52
MaxPhysicalWindowSize : 184,52
KeyAvailable          : False
WindowTitle           : Windows PowerShell
%UserProfile%\Mes documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
$ui = (Get-Host).UI.RawUI

$ui.BackgroundColor = "DarkMagenta"
$ui.ForegroundColor = "DarkYellow"
cls

#$ws = $ui.WindowSize
#$ws.Width = 120
#$ws.Height = 50
#$ui.WindowSize = $ws
Pour modifier les couleurs et la taille de la fenêtre, il est plus simple de modifier les propriétés de la fenêtre.

Propriétés de la fenêtre

PowerShell Cmd
Quick Edit Mode Oui Non
Font Raster Fonts 10x20 Raster Fonts 10x20
Screen 120x3000 80x300
Window 120x50 80x25
Couleur de fond 1, 36, 86 0, 0, 0
Couleur du texte 238, 237, 240 192, 192, 192
Changer la police pour Consolas 14 Lucida Console 14

Couleurs

Ps.svg
# lister et afficher les couleurs
[enum]::GetValues([System.ConsoleColor]) | Foreach-Object {Write-Host $_ -ForegroundColor $_}

Utiliser l'outil Windows Console Colortool pour changer la palette des couleurs.
Il modifie les clés ColorTableXX dans le registre HKEY_CURRENT_USER\Console

Ps.svg
# afficher la table des couleurs courantes
colortool.exe -c

# charger un thème sans modifier la configuration
colortool.exe [scheme]

# modifier le thème par défaut sans modifier le terminal courant
colortool.exe -d [scheme]

# charger un thème et modifier le thème par défaut
colortool.exe -b [scheme]

# retour au thème par défaut
colortool.exe -b cmd-legacy

colortool chercher les thèmes dans le sous-dossier schemes. Il est aussi possible de spécifier le chemin complet vers un thème.
Autres thèmes: iTerm2-Color-Schemes (DarkSide, OneHalfDark)

Darkside_custom.ini
[table]
DARK_BLACK = 0,0,0
DARK_BLUE = 28,152,232
DARK_GREEN = 104,194,86
DARK_CYAN = 28,152,232
DARK_RED = 232,52,28
DARK_MAGENTA = 142,105,201
DARK_YELLOW = 242,211,44
DARK_WHITE = 186,186,186
BRIGHT_BLACK = 186,186,186
BRIGHT_BLUE = 56,123,210
BRIGHT_GREEN = 118,183,104
BRIGHT_CYAN = 61,150,226
BRIGHT_RED = 223,90,79
BRIGHT_MAGENTA = 149,123,189
BRIGHT_YELLOW = 238,214,74
BRIGHT_WHITE = 220,220,220

Background color not working correctly

la console Powershell modifie

  • DarkMagenta (6ème couleur en partant de la gauche) en bleu (1,36,86) pour son background
  • DarkYellow (7ème couleur en partant de la gauche) en gris clair (238,237,240) pour son foreground

Remodifier ces couleurs pour un rendu correspondant au thème:

  • clique-droit dans le titre de la fenêtre → Properties
  • Screen Background: 1ère couleur en partant de la gauche
  • Screen Text: 1ère couleur en partant de la droite

Raccourcis

Les raccourcis vers powershell contiennent une configuration de la palette des couleurs et est prioritaire sur celle du registre.
Les nouveaux raccourci créé prennent la configuration de la palette de couleurs du registre. Remplacer les raccourcis dans %AppData%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell par des nouveaux.

Il est donc possible de créer un raccourci pour chaque palette de couleurs.

Oh-My-Posh

Powershell.svg
# installation
iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/pecigonzalo/Oh-My-Posh/master/install.ps1'))
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# import du module dans le profile
Import-Module "Oh-My-Posh" -DisableNameChecking -NoClobber
$env:USERPROFILE\.oh-my-posh.config.ps1
$plugins= "git", "ls", "ll", "psutils", "psreadline"
# psreadline: historique à la zsh
# ls: ls à la bash
# ll: Get-ChildItem

$theme = "base"
Pour psreadline, télécharger la version nightly build.
Puis remplacer le dossier C:\Program Files\WindowsPowerShell\Modules\PSReadline\2.0.0
  • psutils: ln runat shasum sudo touch

Productivité

cd

Powershell.svg
New-Alias .. cdparent
function cdparent {
    cd ..
}

Set-Alias -Name cd -value cddash -Option AllScope
function cddash {
    if ($args[0] -eq '-') {
        $pwd = $OLDPWD;
    } else {
        $pwd = $args[0];
    }
    $tmp = pwd;

    if ($pwd) {
        Set-Location $pwd;
    }
    Set-Variable -Name OLDPWD -Value $tmp -Scope global;
}

which

Powershell.svg
function which($name) {
    Get-Command $name | Select-Object -ExpandProperty Definition
}

Find file by name

Powershell.svg
function ff { 
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]
        $filename
    )
    Get-ChildItem -Filter "*$filename*" -Recurse -File
}

SHA1

Powershell.svg
function sha1 { 
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]
        $file
    )
    (Get-FileHash -Algorithm SHA1 "$file")."Hash"
}

Alias Git

Powershell.svg
function git-status { git status }
Set-Alias gst git-status

function git-add { git add $args }
New-Alias ga git-add

function git-add-all { git add --all $args }
New-Alias gaa git-add-all

function git-commit { git commit }
Set-Alias gc git-commit

function git-branch { git branch }
Set-Alias gb git-branch

function git-checkout { git checkout }
Set-Alias gco git-checkout

Erreurs

File cannot be loaded because the execution of scripts is disabled on this system

Par défaut les scripts PS ne sont pas autorisé à s'exécuter : « Impossible de charger le fichier ..., car l'exécution de scripts est désactivée sur ce système. »

Powershell.svg
Get-ExecutionPolicy
# Devrait renvoyer Restricted, ce qui signifie qu'aucun script PS ne peut être exécuté
# Pour Windows 8 et 10, le scope par défaut est LocalMachine

# Il faut donc modifier la politique de sécurité
Set-ExecutionPolicy RemoteSigned
# Ainsi les scripts téléchargés devront être signés, et les scripts locaux pourront s'exécuter sans restriction

# Lister les politiques d'exécution pour tous les scopes
Get-ExecutionPolicy -List

Doc

The type initializer for 'Microsoft.PowerShell.PSConsoleReadLine' threw an exception

Problème avec les layouts clavier custom.
Installer la version nightly build du module PSReadLine.

  1. Faire un backup du dossier C:\Program Files\WindowsPowerShell\Modules\PSReadline\2.0.0
  2. Télécharger la version nightly build du module PSReadLine
  3. Dans C:\Program Files\WindowsPowerShell\Modules\PSReadline\2.0.0
    1. Remplacer les fichiers suivants: PSReadLine.format.ps1xml, PSReadline.psd1, PSReadline.psm1
    2. Copier Microsoft.PowerShell.PSReadLine2.dll et supprimer Microsoft.PowerShell.PSReadLine.dll
    3. Conserver les dossiers en et fr, et ne pas copier en-US