Liens
Modules
PowerShell Gallery
|
Get-Module
Get-Module -ListAvailable
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
|
|
echo $env:PSModulePath
|
 |
PSReadLine 2.0 est déjà installé et importé. |
|
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
|
choco install fd
|
|
choco install ripgrep
|
|
choco install gsudo
sudo
sudo -n
sudo md "C:\Windows\Test"
sudo config CacheMode Auto
|
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
|
Set-PSReadlineOption -BellStyle None
|
Connaitre la version de PowerShell installée
|
$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:
regedit → Computer\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:
- New Key → PowerShell2
- (Default) = @shell32.dll,-8508
- New String Value → NoWorkingDirectory
- New String Value → Icon = C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
- New DWORD (32-bit) Value → ShowBasedOnVelocityId = 639bc8 (Hexadecimal)
- New Key → command
- (Default) = powershell.exe -noexit -command Set-Location -literalPath '%V'
|
. C:\chemin\vers\fichier.ps1
. (join-path -path $PSScriptRoot -childpath "fichier.ps1")
|
 |
$PSScriptRoot permet d'obtenir le chemin vers le script courant. |
|
$code = "start-service 'my_service' -PassThru"
Start-Process -FilePath powershell.exe -ArgumentList $code -verb RunAs -WorkingDirectory C:
|
|
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit
}
Write-Host -NoNewLine "`nPress any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
Extension « PowerShell Tools for Visual Studio 2013 » à installer pour pouvoir éditer les fichiers PowerShell dans Visual Studio.
Désarchiver le module dans « Mes Documents\WindowsPowerShell\Modules »
|
Import-Module PowerTab
|
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
|
Import-Module "PowerTab" -ArgumentList "C:\Users\Nicolas\Documents\WindowsPowerShell\PowerTabConfig.xml"
|
%UserProfile%\My Documents\WindowsPowerShell\Modules\PowerTab\TabExpansion.ps1
|
$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. |
|
get-alias
gal
alias <mon-alias>
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
|
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
|
|
new-item -path $profile -itemtype file -force
echo $profile
|
%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
|
. %UserProfile%\Documents\WindowsPowerShell\Alias.ps1
|
|
.$profile
|
(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
|
 |
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
|
[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
|
colortool.exe -c
colortool.exe [scheme]
colortool.exe -d [scheme]
colortool.exe -b [scheme]
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
|
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. |
|
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-Module "Oh-My-Posh" -DisableNameChecking -NoClobber
|
$env:USERPROFILE\.oh-my-posh.config.ps1
|
$plugins= "git", "ls", "ll", "psutils", "psreadline"
$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é
|
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;
}
Set-Alias -Name cd -value cddash -Option AllScope
|
..
|
function cdparent {
cd ..
}
New-Alias .. cdparent
|
which
|
function which($name) {
Get-Command $name | Select-Object -ExpandProperty Definition
}
|
Alias Git
|
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. »
|
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned
Get-ExecutionPolicy -List
|
Doc
Problème avec les layouts clavier custom.
Installer la version nightly build du module PSReadLine.
- Faire un backup du dossier C:\Program Files\WindowsPowerShell\Modules\PSReadline\2.0.0
- Télécharger la version nightly build du module PSReadLine
- Dans C:\Program Files\WindowsPowerShell\Modules\PSReadline\2.0.0
- Remplacer les fichiers suivants: PSReadLine.format.ps1xml, PSReadline.psd1, PSReadline.psm1
- Copier Microsoft.PowerShell.PSReadLine2.dll et supprimer Microsoft.PowerShell.PSReadLine.dll
- Conserver les dossiers en et fr, et ne pas copier en-US