« Powershell configuration » : différence entre les versions
(41 versions intermédiaires par le même utilisateur non affichées) | |||
Ligne 6 : | Ligne 6 : | ||
[https://www.powershellgallery.com/items PowerShell Gallery] | [https://www.powershellgallery.com/items PowerShell Gallery] | ||
<kode lang='powershell'> | <kode lang='powershell'> | ||
# | # search for a module | ||
Find-Module <ModuleName> | |||
# install / uninstall a module | |||
Install-Module -Name <ModuleName> -Scope CurrentUser | |||
Uninstall-Module -Name <ModuleName> | |||
# list loaded modules | |||
Get-Module | Get-Module | ||
# list installed modules | |||
Get-Module -ListAvailable | |||
# | # load / unload a module | ||
Import-Module <ModuleName> | Import-Module <ModuleName> | ||
Remove-Module <ModuleName> | Remove-Module <ModuleName> | ||
# Installer un module dans une console ouverte en mode administrateur | # Installer un module dans une console ouverte en mode administrateur | ||
Ligne 22 : | Ligne 28 : | ||
</kode> | </kode> | ||
<filebox fn=' | <filebox fn='$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1' lang=powershell> | ||
Import-Module <ModuleName> | Import-Module <ModuleName> | ||
</filebox> | </filebox> | ||
{| class="wikitable wtp wtmono1" | {| class="wikitable wtp wtmono1" | ||
|- | |- | ||
| [https://www.powershellgallery.com/packages/posh-git posh-git] || provides prompt with Git status summary information and tab completion for Git commands, parameters, remotes and branch names | | [https://www.powershellgallery.com/packages/posh-git posh-git] || provides prompt with Git status summary information and tab completion for Git commands, parameters, remotes and branch names | ||
|- | |- | ||
| [https://github.com/DTW-DanWard/PowerShell-Beautifier PowerShell Beautifier] || format powershell code | | [https://github.com/DTW-DanWard/PowerShell-Beautifier PowerShell Beautifier] || format powershell code | ||
|- | |||
| [https://www.powershellgallery.com/packages/Recycle Recycle ] || move files and folders in the recycle bin | |||
|} | |} | ||
<kode lang='ps'> | <kode lang='ps'> | ||
Ligne 71 : | Ligne 75 : | ||
| Alt + % || Replace all aliases with the full command | | Alt + % || Replace all aliases with the full command | ||
|} | |} | ||
== [https://www.powershellgallery.com/packages/Terminal-Icons Terminal-Icons] == | |||
Show file and folder icons while listing items. Also colors items. | |||
<filebox fn='$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'> | |||
Set-Alias l Get-ChildItem-Format-Wide | |||
function Get-ChildItem-Format-Wide { | |||
Get-ChildItem | Format-Wide | |||
} | |||
Set-Alias ll Get-ChildItem-Format-List | |||
function Get-ChildItem-Format-List { | |||
Get-ChildItem | Format-List | |||
} | |||
</filebox> | |||
== [https://www.powershellgallery.com/packages/oh-my-posh oh-my-posh] == | |||
Prompt theme engine. | |||
{{warn | Icons rendering is [https://stackoverflow.com/questions/67608580/how-to-fix-powershell-7-fonts-not-showing-correctly-oh-my-posh bugged].<br> | |||
Terminal uses [https://ftp.nluug.nl/networking/kermit/public_html/black.html UCS-2] code and not UTF-8.<br> | |||
Use icon code from {{boxx|Terminal-Icons}}.}} | |||
* install a [https://www.nerdfonts.com/font-downloads Nerd font] | |||
<filebox fn='$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 '> | |||
Import-Module oh-my-posh | |||
# set the robbyrusseltheme | |||
Set-PoshPrompt -Theme ~\Documents\WindowsPowerShell\Modules\oh-my-posh\themes\robbyrussel.omp.json | |||
</filebox> | |||
<filebox fn='robbyrussel2.omp.json' collapsed> | |||
{ | |||
"blocks": [ | |||
{ | |||
"type": "prompt", | |||
"alignment": "left", | |||
"segments": [ | |||
{ | |||
"type": "exit", | |||
"style": "plain", | |||
"foreground": "#98C379", | |||
"foreground_templates": ["{{ if gt .Code 0 }}#BF616A{{ end }}"], | |||
"properties": { | |||
"template": "\uF061", | |||
"postfix": "", | |||
"always_enabled": true | |||
} | |||
}, | |||
{ | |||
"type": "path", | |||
"style": "plain", | |||
"foreground": "#56B6C2", | |||
"properties": { | |||
"style": "folder", | |||
"home_icon": "\uF015" | |||
} | |||
}, | |||
{ | |||
"type": "git", | |||
"style": "plain", | |||
"foreground": "#D0666F", | |||
"properties": { | |||
"branch_icon": "", | |||
"prefix": "<#5FAAE8>(</>", | |||
"postfix": "<#5FAAE8>)</> ", | |||
"template": "{{ .HEAD }}" | |||
} | |||
} | |||
] | |||
} | |||
], | |||
"final_space": false, | |||
"console_title": true, | |||
"console_title_style": "template", | |||
"console_title_template": "{{ .Folder }}{{if .Root}} (admin){{end}}" | |||
} | |||
</filebox> | |||
== [https://www.powershellgallery.com/packages/Get-ChildItemColor Get-ChildItemColor] == | |||
Provides colored version of the {{boxx|Get-ChildItem}} Cmdlet. | |||
<kode lang='powershell'> | |||
Install-Module -AllowClobber Get-ChildItemColor -Scope CurrentUser | |||
# -AllowClobber option is needed so Get-ChildItemColor may override the existing command Out-Default. | |||
</kode> | |||
<filebox fn='$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'> | |||
If (-Not (Test-Path Variable:PSise)) { # Only run this in the console and not in the ISE | |||
Import-Module Get-ChildItemColor | |||
Set-Alias l Get-ChildItemColorFormatWide -option AllScope | |||
Set-Alias ll Get-ChildItem -option AllScope | |||
} | |||
</filebox> | |||
Another alternative is the [https://github.com/Davlind/PSColor PSColor] module. | |||
= Bash tools = | = Bash tools = | ||
Ligne 78 : | Ligne 176 : | ||
<kode lang='ps'> | <kode lang='ps'> | ||
choco install fd | choco install fd | ||
</kode> | |||
== [https://github.com/bootandy/dust dust] ([[Bash_command_line#dust|bash]]) == | |||
<kode lang='ps'> | |||
choco install dust | |||
</kode> | </kode> | ||
== [https://github.com/BurntSushi/ripgrep ripgrep] ([[Bash_command_line#ripgrep|bash]]) == | == [https://github.com/BurntSushi/ripgrep ripgrep] ([[Bash_command_line#ripgrep|bash]]) == | ||
<kode lang='ps'> | <kode lang='ps'> | ||
winget install BurntSushi.ripgrep.MSVC | |||
choco install ripgrep | choco install ripgrep | ||
</kode> | </kode> | ||
Ligne 87 : | Ligne 191 : | ||
== [https://github.com/gerardog/gsudo gsudo] == | == [https://github.com/gerardog/gsudo gsudo] == | ||
<kode lang='ps'> | <kode lang='ps'> | ||
winget install gerardog.gsudo | |||
choco install gsudo | choco install gsudo | ||
Ligne 103 : | Ligne 208 : | ||
== [https://github.com/DuFace/PoShWarp Warp Directory] ([[Zsh#wd_-_Warp_Directory|bash]]) == | == [https://github.com/DuFace/PoShWarp Warp Directory] ([[Zsh#wd_-_Warp_Directory|bash]]) == | ||
Télécharger {{boxx|PoShWarp.psm1}} et le copier dans {{boxx|WindowsPowerShell\Modules\PoShWarp}}<br> | {{warn | L'installation du module via PsGet {{boxx|Install-Module PoShWarp}} ne fonctionne pas. Il faut l'installer mauellement.}} | ||
Télécharger {{boxx|PoShWarp.psm1}} et le copier dans {{boxx|$home\Documents\WindowsPowerShell\Modules\PoShWarp}}<br> | |||
Le module sera importer automatiquement au démarrage de powershell. | Le module sera importer automatiquement au démarrage de powershell. | ||
== [http://gnuwin32.sourceforge.net/packages/sed.htm sed] ([[Bash_command_line#sed_.28Stream_EDitor.29|bash]]) == | |||
<kode lang='ps'> | |||
choco install sed | |||
</kode> | |||
= Désactiver le beep = | = Désactiver le beep = | ||
Ligne 135 : | Ligne 246 : | ||
= Ouvrir un terminal PowerShell depuis Explorer = | = Ouvrir un terminal PowerShell depuis Explorer = | ||
Shift + clique droit → Open PowerShell window here | * {{boxx|Shift + clique droit}} → {{boxx|Open PowerShell window here}} | ||
Autre solution: créer sa propre entrée dans le menu contextuel d'Explorer<br> | |||
{{boxx|regedit}} → {{boxx|Computer\HKEY_CLASSES_ROOT\Directory\Background\shell}} | {{boxx|regedit}} → {{boxx|Computer\HKEY_CLASSES_ROOT\Directory\Background\shell}}<br> | ||
Il | Il n'est malheureusement pas possible de supprimer la String-Value {{boxx|Extended}} du dossier {{boxx|Powershell}} pour rendre l'entrée {{boxx|Open PowerShell window here}} accessible sans avoir à appuyer sur {{boxx|Shift}}.<br> | ||
<kode lang='reg'> | |||
[HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell2] | |||
@="@shell32.dll,-8508" | |||
"NoWorkingDirectory"="" | |||
"ShowBasedOnVelocityId"=dword:00639bc8 | |||
[HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell2\command] | |||
@="powershell.exe -noexit -command Set-Location -literalPath '%V'" | |||
</kode> | |||
= [http://www.thomas-franke.net/including-scripts-functions-modules/ Inclure des fichiers] = | = [http://www.thomas-franke.net/including-scripts-functions-modules/ Inclure des fichiers] = | ||
Ligne 206 : | Ligne 319 : | ||
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | ||
</kode> | </kode> | ||
= [http://powertab.codeplex.com/ Completion - PowerTab] = | = [http://powertab.codeplex.com/ Completion - PowerTab] = | ||
Ligne 419 : | Ligne 529 : | ||
{{info | Il est donc possible de créer un raccourci pour chaque palette de couleurs.}} | {{info | Il est donc possible de créer un raccourci pour chaque palette de couleurs.}} | ||
= [https://github.com/pecigonzalo/Oh-My-Posh Oh-My-Posh] = | = [https://github.com/pecigonzalo/Oh-My-Posh Oh-My-Posh from pecigonzalo] = | ||
<kode lang='powershell'> | <kode lang='powershell'> | ||
# installation | # installation | ||
Ligne 425 : | Ligne 535 : | ||
</kode> | </kode> | ||
<filebox fn=' | <filebox fn='$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1' lang=powershell> | ||
# import du module dans le profile | # import du module dans le profile | ||
Import-Module "Oh-My-Posh" -DisableNameChecking -NoClobber | Import-Module "Oh-My-Posh" -DisableNameChecking -NoClobber | ||
Ligne 431 : | Ligne 541 : | ||
<filebox fn='$env:USERPROFILE\.oh-my-posh.config.ps1' lang=powershell> | <filebox fn='$env:USERPROFILE\.oh-my-posh.config.ps1' lang=powershell> | ||
# copy the template configuration from template\oh-my-posh.config.ps1 | |||
$plugins= "git", "ls", "ll", "psutils", "psreadline" | $plugins= "git", "ls", "ll", "psutils", "psreadline" | ||
# psreadline: historique à la zsh | # psreadline: historique à la zsh | ||
Ligne 447 : | Ligne 558 : | ||
* [http://windows-powershell-scripts.blogspot.com/2009/07/cd-change-to-previous-working-directory.html cd -] | * [http://windows-powershell-scripts.blogspot.com/2009/07/cd-change-to-previous-working-directory.html cd -] | ||
<kode lang='powershell' collapsed> | <kode lang='powershell' collapsed> | ||
New-Alias .. | New-Alias .. Set-Location-To-Parent | ||
function | function Set-Location-To-Parent { | ||
Set-Location .. | |||
} | } | ||
Set-Alias - | Set-Alias cd Set-Location-Plus -Option AllScope | ||
function | function Set-Location-Plus { | ||
if ($args[0] -eq '-') { | if ($args.Length -eq 0) { | ||
$ | $new_location = $env:USERPROFILE; | ||
} else { | } | ||
$ | elseif ($args[0] -eq '-') { | ||
$new_location = $set_location_plus_previous_location; | |||
} | |||
else { | |||
$new_location = $args[0]; | |||
} | } | ||
$current_location = Get-Location; | |||
Set-Variable -Name set_location_plus_previous_location -Value $current_location -Scope global; | |||
Set-Location $new_location; | |||
Set-Variable -Name | |||
} | } | ||
</kode> | </kode> | ||
Ligne 501 : | Ligne 614 : | ||
== Alias Git == | == Alias Git == | ||
<kode lang='powershell' collapsed> | <kode lang='powershell' collapsed> | ||
function git-status { git status } | function invoke-git-status { git status } | ||
Set-Alias gst git-status | Set-Alias gst invoke-git-status | ||
function git-add { git add $args } | function invoke-git-add { git add $args } | ||
New-Alias ga git-add | New-Alias ga git-add | ||
function git-add-all { git add --all $args } | function invoke-git-add-all { git add --all $args } | ||
New-Alias gaa git-add-all | New-Alias gaa invoke-git-add-all | ||
function git-commit { git commit } | function invoke-git-commit { git commit } | ||
Set-Alias gc git-commit | Set-Alias gc invoke-git-commit | ||
function git-branch { git branch } | function invoke-git-branch { git branch } | ||
Set-Alias gb git-branch | Set-Alias gb invoke-git-branch | ||
function git-checkout { git checkout } | function invoke-git-checkout { git checkout } | ||
Set-Alias gco git-checkout | Set-Alias gco invoke-git-checkout | ||
</kode> | </kode> | ||
Ligne 524 : | Ligne 637 : | ||
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. »<br/> | 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. »<br/> | ||
<kode lang=powershell> | <kode lang=powershell> | ||
Get-ExecutionPolicy | # get the execution policy for each scope | ||
Get-ExecutionPolicy -List | |||
# | # change the execution policy for the current user to RemoteSigned | ||
Set-ExecutionPolicy RemoteSigned | Set-ExecutionPolicy RemoteSigned -Scope CurrentUser | ||
</kode> | </kode> | ||
Dernière version du 1 février 2024 à 17:47
Liens
Modules
# search for a module
Find-Module <ModuleName>
# install / uninstall a module
Install-Module -Name <ModuleName> -Scope CurrentUser
Uninstall-Module -Name <ModuleName>
# list loaded modules
Get-Module
# list installed modules
Get-Module -ListAvailable
# load / unload a module
Import-Module <ModuleName>
Remove-Module <ModuleName>
# Installer un module dans une console ouverte en mode administrateur
Install-Module -Name <ModuleName>
Uninstall-Module -Name <ModuleName>
Find-Module <ModuleName>
|
$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 |
Import-Module <ModuleName>
|
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 |
Recycle | move files and folders in the recycle bin |
echo $env:PSModulePath
# %ProgramFiles%\WindowsPowerShell\Modules
# %HomePath%\Documents\WindowsPowerShell\Modules
|
PSReadLine
![]() |
PSReadLine 2.0 est déjà installé et importé. |
# 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
|
↑ ↓ | 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 |
Terminal-Icons
Show file and folder icons while listing items. Also colors items.
$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 |
Set-Alias l Get-ChildItem-Format-Wide
function Get-ChildItem-Format-Wide {
Get-ChildItem | Format-Wide
}
Set-Alias ll Get-ChildItem-Format-List
function Get-ChildItem-Format-List {
Get-ChildItem | Format-List
}
|
oh-my-posh
Prompt theme engine.
![]() |
Icons rendering is bugged. Terminal uses UCS-2 code and not UTF-8. |
- install a Nerd font
$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 |
Import-Module oh-my-posh
# set the robbyrusseltheme
Set-PoshPrompt -Theme ~\Documents\WindowsPowerShell\Modules\oh-my-posh\themes\robbyrussel.omp.json
|
robbyrussel2.omp.json |
Get-ChildItemColor
Provides colored version of the Get-ChildItem Cmdlet.
Install-Module -AllowClobber Get-ChildItemColor -Scope CurrentUser
# -AllowClobber option is needed so Get-ChildItemColor may override the existing command Out-Default.
|
$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 |
If (-Not (Test-Path Variable:PSise)) { # Only run this in the console and not in the ISE
Import-Module Get-ChildItemColor
Set-Alias l Get-ChildItemColorFormatWide -option AllScope
Set-Alias ll Get-ChildItem -option AllScope
}
|
Another alternative is the PSColor module.
Bash tools
fd (bash)
choco install fd |
dust (bash)
choco install dust |
ripgrep (bash)
winget install BurntSushi.ripgrep.MSVC choco install ripgrep |
gsudo
winget install gerardog.gsudo
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)
![]() |
L'installation du module via PsGet Install-Module PoShWarp ne fonctionne pas. Il faut l'installer mauellement. |
Télécharger PoShWarp.psm1 et le copier dans $home\Documents\WindowsPowerShell\Modules\PoShWarp
Le module sera importer automatiquement au démarrage de powershell.
sed (bash)
choco install sed |
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
Autre solution: créer sa propre entrée dans le menu contextuel d'Explorer
regedit → Computer\HKEY_CLASSES_ROOT\Directory\Background\shell
Il n'est malheureusement pas possible de supprimer la String-Value Extended du dossier Powershell pour rendre l'entrée Open PowerShell window here accessible sans avoir à appuyer sur Shift.
[HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell2] @="@shell32.dll,-8508" "NoWorkingDirectory"="" "ShowBasedOnVelocityId"=dword:00639bc8 [HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell2\command] @="powershell.exe -noexit -command Set-Location -literalPath '%V'" |
Inclure des fichiers
# 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
$code = "start-service 'my_service' -PassThru"
Start-Process -FilePath powershell.exe -ArgumentList $code -verb RunAs -WorkingDirectory C:
|
A self elevating PowerShell script
# 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")
|
Completion - PowerTab
Désarchiver le module dans « Mes Documents\WindowsPowerShell\Modules »
# 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. |
# 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
# 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 |
# 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 |
# 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
# 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
# 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 |
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 from pecigonzalo
# installation
iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/pecigonzalo/Oh-My-Posh/master/install.ps1'))
|
$env: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 |
# copy the template configuration from template\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
|
which
|
Find file by name
|
SHA1
|
Alias Git
|
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 the execution policy for each scope
Get-ExecutionPolicy -List
# change the execution policy for the current user to RemoteSigned
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
|
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.
- 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