Powershell

De Banane Atomic
Aller à la navigationAller à la recherche

Liens

Script template

À placer au début du script (en dessous de Param).

Ps.svg
# Renforce les règles de vérification et créé une erreur si elles ne sont pas respectées
Set-StrictMode -Version Latest

# Stop le script à la première erreur (par défaut à Continue)
$ErrorActionPreference = "Stop"
# en ligne de commande: .\MyScript.ps1 -ErrorAction Stop

# Force tous les Cmdlet à s'arrêter à la première erreur
$PSDefaultParameterValues['*:ErrorAction'] = 'Stop'

Astuces

Powershell.svg
# commentaire
<# commentaires 
   commentaires #>

# multilines command
command -option1 `
        -option2

# tester une commande: affiche le résultat mais n’exécute pas la commande
Commande -WhatIf

# exécuter un fichier depuis la console cmd.exe
powershell -file MonFichier.ps1
# exécuter une commande depuis la console cmd.exe
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "& 'C:\dossier\script.ps1' args"

# appeler un autre script powershell
& 'C:\dossier\script.ps1' args

# Supprimer l'attribut Read-Only
sp file.txt IsReadOnly $false

# ouvrir explorer (Invoke-Item)
ii .

# lancer internet explorer
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate2("http://www.google.com")
$ie.Visible = $true

# tester si la console est en mode admin
[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")

Variables

Pas de - dans les noms des variables.
Ps.svg
$my_var = "value"

Environment Variables

Ps.svg
# list all environment variables
Get-Childitem env:
$env:userprofile C:\Users\<user>
$env:appdata C:\Users\<user>\AppData\Roaming
$env:ProgramFiles C:\Program Files
[environment]::getfolderpath("mydocuments") C:\Users\<user>\Documents

Automatic Variables

$_ the current object in the pipeline
$home C:\Users\<user>
$Pwd full path of the current directory
$PSCommandPath path of the script file that is being executed
$PSScriptRoot path of the script directory that is being executed

echo, Write-Host

Ps.svg
echo 'my text'

# saut de ligne
echo line1 line2
echo line1`nline2
echo line1([system.environment]::newline)line2

# colors
Write-Host -foregroundcolor green -backgroundcolor black Mon Message

# erreur
Write-Error "Error!"
Couleurs disponibles
Black Blue Cyan DarkBlue
DarkCyan DarkGray DarkGreen DarkMagenta
DarkRed DarkYellow Gray Green
Magenta Red White Yellow
echo is an alias of Write-Output

PSWriteColor

Powershell.svg
# installation du module (console administrateur)
Install-Module -Name PSWriteColor

Import-Module PSWriteColor

Write-Color "Red ", "Green ", "Yellow " -Color Red, Green, Yellow
wc "Red ", "Green ", "Yellow " -C Red, Green, Yellow
# -StartTab 1     ajoute une tabulation avant d'afficher le texte
# -LinesBefore 1  passe une ligne avant d'afficher le texte
# -LinesAfter 1   passe une ligne après avoir afficher le texte
# -LogFile "C:\log.txt"  écrit dans un fichier de log [YYYY-MM-DD HH:mm:ss]Texte

Read input

Ps.svg
# lire l'entrée clavier
$input = Read-Host 'Question?'

# Press any key to continue
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

GridView

Ps.svg
# afficher une fenêtre avec une grille
New-Object Net.Webclient | Get-Member | Out-GridView

# permettre de séléctionner des éléments dans la grille et de s'en servir comme paramètres d'entrée
Get-Service |
    Where Status -eq Stopped |
    Out-GridView -PassThru |
    Start-Service

Types

String

Ps.svg
echo "Escape `"double-quotes`" `$1"  # "double-quotes" $1
echo "Retour à la ligne `r`n"

# concaténation de string
echo 'Text1 - ' + "Text2: ${Var1}, $Var2"
echo "Text: $(command)"

# here-string: multiline string @""@ @''@
echo @"
First line
Second line
"Quotes don't need to be escaped"
Plus, you can include variables: $MyVar
"@ # has to be at the beginning of a new line

'ABC' -replace 'B','X'   # AXC
'ABC' -replace '\w$','X' # ABX
'ABC' -replace '^(\w)(.+)(\w)$','$3$2$1'  # CBA
'ABC' -replace '^(?<first>\w)(.+)(?<last>\w)$','${last}$1${first}'  # CBA
'ABC' -replace 'B'      # AC
'ABC'.replace('B', '')  # AC

'abc'.toupper()  # ABC

Test string

Ps.svg
$MyString -like 'xxx*'  # Returns true when string matches wildcard (-notlike)

$MyString -match 'xxx.+'  # Returns true when string matches regex (-notmatch)

$MyString.startswith('xxx')

if ($MyString)  # not null and not empty
if (!$MyString)  # null or empty

Date

Ps.svg
Get-Date -Format 'yyyy-MM'  # 2020-01

Tableau / array

Ps.svg
$myArray = @()  # empty
$myArray = 1, 2, 3
$myArray += 4

$myArray[1..2]  # 2 3
$myArray[-1]    # 4

$myArray -ne 2  # 1 3 4
$myArray -gt 2  # 3 4

[array]::Reverse($myArray)  # 4 3 2 1

$one, $two, $rest = $myArray  # $one = 1, $two = 2, $rest = 3, 4

Hash table

Ps.svg
$myHashTable = @{}  # empty
$myHashTable.Key1 = "Value1"
$myHashTable = @{
    Key1 = "Value1"
    Key2 = "Value2"
}

$myValue = $myHashTable.$myKey

"All keys: $($myHashTable.keys)"
"All values: $($myHashTable.values)"

if (!$myHashTable.contains($myKey))

PSObject

Ps.svg
$obj = New-Object PSObject -Property @{
    Prop1 = "Value1"
    Prop2 = "Value2"
}

if else

Powershell.svg
$nombre = 10
if ($nombre -eq 10) {
    "Le nombre est 10."
}
elseif (($nombre -gt 5) -and ($nombre -lt 10) -or ($nombre -eq 222)) {
    "Le nombre est entre 5 et 10 ou égal à 222."
}
elseif (!($nombre -eq 333)) {
    "Le nombre est différent de 333."
}
else { "Surement 333" }
Opérateur Description Opérateur Description
-eq == -ceq == case senstivie
-ne !=
-lt < -le <=
-gt > -ge >=
-not ! !
-and && -or ||
-band & -bor |

Test string

Bash.svg
if ([string]::IsNullOrEmpty($monString))

The String’s the Thing

switch

Powershell.svg
switch ($var)
{
    'value1' { echo $var }
    'value2' { echo $var }
    default { echo 'unknown value' }
}

$result = switch ($var)
{
    'Word1' { 'Value1' }
    'Word2' { 'Value2' }
    default { 'Default Value' }
}

Select

Powershell.svg
# parmi les résultats de command, n'affiche que UnePropriété (select = Select-Object)
command | select UnePropriété
# afficher seulement la valeur de UnePropriété (exp = expand = ExpandProperty)
(command).UnePropriété
command | select -exp UnePropriété
 
# parmi les résultats de command, n'affiche que les 10 premiers résultats
command | select -first 10

Where ?

Powershell.svg
1..4 | ? {$_ % 2 -eq 0}  # 2 4
Alias: Where-Object where ?

ForEach %

Ps.svg
1..4 | % { $_ * 2 }  # 2 4 6 8

Fonctions

Powershell.svg
Function TestName {
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]
        $nom
    )
    if ($nom -eq "moi")
    {
        return $true
    }
    return $false
}

TestName "moi"
# True
La fonction doit être déclarée avant son utilisation.

Paramètres et Arguments

Powershell.svg
# doit se situer à la première ligne exécutable (au dessus de Set-StrictMode)
Param (
  # avec une valeur par défaut
  [string] $Name = "initial value",

  # paramètre obligatoire
  # position permet de définir le paramètre sans son nom
  [Parameter(Mandatory = $true, Position = 0)]
  [string] $Name,

  # True par défaut. Valeurs: $true ou $false.
  [Parameter(Position = 1)]
  [bool] $BooleanValue,

  # no parameter passed means false, and -SwitchValuemeans true
  [switch] $SwitchValue,

  # avec des alias (-e -ef)
  [Alias('e','ef')]
  [string] $excludeFolder
)

# utilisation avec les noms des paramètres
.\MonScript.ps1 -Name MyName -BooleanValue $false -SwitchValue

# utilisation avec les positions
.\MonScript.ps1 MyName $false
Mandatory = $true , demande de manière interactive les paramètres s'ils ne sont pas spécifiés.
$args fonctionne avec les arguments passés à une fonction mais pas avec ceux passés à un script.

Exclusive groups of mandatory elements

Powershell.svg
# ok: .\MyScript -Environment env1
# ok: .\MyScript -Server srv1 -Database db1
# ko: .\MyScript -Environment env1 -Server srv1 -Database db1
[CmdletBinding(DefaultParameterSetName='Env')]  # by default, Env is used
Param (
    [Parameter(ParameterSetName = 'Env', Mandatory = $true)]
    [string] $Environment,
    [Parameter(ParameterSetName = 'Srv', Mandatory = $true)]
    [string] $Server
    [Parameter(ParameterSetName = 'Srv', Mandatory = $true)]
    [string] $Database
)

# to know which ParameterSetName has been used
echo $PSCmdlet.ParameterSetName  # Env or Srv

Common parameters

Parameter
-Debug
-ErrorAction
-ErrorVariable
-OutBuffer
-OutVariable
-Verbose
-WarningAction
-WarningVariable
Ps.svg
[CmdletBinding()]  # add this line at the top of the script file
Param ()

if ($PSBoundParameters['Verbose'])  # test if Verbose has been passed as parameter

Files and folders

List

Ps.svg
# display names only
ls C:\Dossier -Name

# display fullnames (C:\Dossier\filename.ext)
ls C:\Dossier | % FullName

# display names without the extension
ls C:\Dossier | % BaseName

# filter
ls C:\Dossier *.txt
# exclude *.txt et *.dll
ls C:\Dossier -exclude *.txt, *.dll

# filter against RegEx (-NotMatch, -NotLike)
ls C:\Dossier | ? Name -Match "\.txt$"  # RegEx
ls C:\Dossier | ? Name -Like "*.txt"  # Wildcard Expression

# lister toutes les DLL et EXE avec leurs versions
ls *.dll,*.exe | % { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion }
ls dir gci are aliases of Get-ChildItem
filter et exclude ne fonctionnent pas en même temps.
Utiliser * dans le chemin à la place de filter
-exclude only applies to basenames of items myfile.txt, not the fullname C:\folder\myfile.txt

sort

Ps.svg
# sort by name
ls C:\Dossier | sort

# sort by LastWriteTime, last modified first
ls C:\Dossier | sort -property LastWriteTime -Descending

Search by name

Ps.svg
# look recursively for all the *.txt files
ls -r -ErrorAction SilentlyContinue "*.txt"

Search by file content

Ps.svg
# look recursively for files which contains xxx
ls -r C:\Dossier | sls "xxx" | group path | % name

# display all the occurences of xxx with 2 lines before and after
ls -r C:\Dossier | sls "xxx" -context 2
sls is an alias of Select-String
context ne semble plus fonctionner

Read / Get content

Ps.svg
# return an array of newline-delimited strings
$content = Get-Content .\file.txt

# return a string
$content = Get-Content .\file.txt -raw

# tail equivalent: display what is appended to the file in realtime
Get-Content .\file.txt -Wait -Tail 1

Write / Set content

Ps.svg
Set-Content -Encoding UTF8 -Path .\file.txt -Value 'Text'
Encoding values
Default UTF-8 without BOM
UTF8 UTF-8 with BOM

Replace content

The default encoding is UTF-8 without BOM
Ps.svg
(Get-Content .\file.txt) -replace 'Text', 'Content' | Set-Content .\file.txt
(Get-Content .\file.txt) -replace 'var=(\w+);', "var=$new_value;" | Set-Content .\file.txt

# multi-lines: remove <tag> and its content
(Get-Content .\file.txt -raw) -replace '(?s)<tag>.+</tag>' | Set-Content .\file.txt
# (?s) single line mode: add line breaks in the matching characters for .

Delete files based on pattern

Ps.svg
# delete all the *.txt files
ls *.txt | Remove-Item

Créer / supprimer un dossier

Ps.svg
# suppression d'un dossier et de son contenu
rm -r -fo C:\Dossier
# -r  / -recurse
# -fo / -force
# -ErrorAction Continue

# test before delete to avoid error
if (test-path C:\Dossier) { rm -r C:\Dossier }

# | Out-Null permet de masquer la sortie
ni C:\Dossier -type directory | Out-Null

# -force écrase le fichier s'il existe déjà, pour un dossier cela permet juste d'éviter l'erreur « Item already exists »
ni C:\Dossier -type directory -force
Alias de Remove-Item: del, erase, rd, ri, rm, rmdir
Alias de New-Item: ni

Remove-Item

Path

Powershell.svg
# dossier1\dossier2
join-path dossier1 dossier2
join-path -path dossier1 -childpath dossier2  
join-path -path dossier1\ -childpath \dossier2\
 
join-path -path dossier1 -childpath (join-path -path dossier2 -childpath dossier3)
# dossier1\dossier2\dossier3

# utilisation du Framework .NET
[System.IO.Path]::Combine("C:\Dossier1", "Dossier2", "Dossier3")
# C:\Dossier1\Dossier2\Dossier3
 
# test si le chemin c:\dossier existe
if (Test-Path C:\Dossier -PathType Container) { }

# test si le chemin c:\dossier existe
if (Test-Path C:\Dossier\file.txt -PathType Leaf) { }

Copy-Item

Powershell.svg
# copie de Fichier.txt dans Dossier2 sous le nom de Fichier2.txt
# dans ce cas Dossier2 n'est pas créé s'il n'existe pas
cp C:\Dossier\Fichier.txt C:\Dossier2\Fichier2.txt
 
# copie récursive de Dossier dans Dossier2 (création de Dossier2 s'il n'existe pas)
cp -recurse C:\Dossier C:\Dossier2
 
# copie récursive de l'arborescence de Dossier dans Dossier2 et copie des fichiers *.txt exclusivement
cp C:\Dossier C:\Dossier2 -recurse -filter *.txt

# copie tous les *.txt en excluant les *.bak.txt
cp C:\Dossier\*.txt C:\Dossier2 -exclude *.bak.txt

# copie récursive avec exclusion
$from = convert-path (join-path $Path1 '..\Dossier') # convert-path pour supprimer les ..
ls -r $from -exclude *.pdb, *.xml | % {
    cp $_.FullName (join-path $to $_.FullName.Substring($from.length))
}
Alias Copy-Item copy cp cpi
Exclude ne fonctionne pas avec les répertoires

Measure / Count

Powershell.svg
ls | measure
# Count    : 8   
# Average  :     
# Sum      :     
# Maximum  :     
# Minimum  :     
# Property :     

# compter le nombre d'éléments dans le dossier courant
(ls | measure).Count;

Log

Ps.svg
# log in MyProgram.log in the same folder
Start-Transcript -path $PSCommandPath.replace('.ps1', '.log')

Échapper les caractères spéciaux

Powershell.svg
echo '$dollar'  # $dollar
echo `$dollar   # $dollar

Encoding

Si la sortie affiche des caractères inattendus, utiliser l'encodage UTF-8 avec BOM.

Expressions rationnelles

Shutdown - Restart

Ps.svg
Stop-Computer
Restart-Computer

Batch commands

Active Directory

Powershell.svg
Import-Module activedirectory

Get-ADUser -filter *

Process

Ps.svg
# list processes by name
ps | ? name -eq 'firefox'
Get-Process | ? { $_.ProcessName -like "*git*" }

# list processes by path
ps | ? Path -match 'firefox.exe$'

# list processes which use a port
Get-Process -Id (Get-NetTCPConnection -LocalPort 135).OwningProcess

# test is a process is running
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
    echo 'firefox is running'
}

# open a new powershell console
start-process powershell -ArgumentList "-NoProfile -NoExit -Command echo $var"

Services

Powershell.svg
# affiche l'état d'un service
get-service 'SQLBrowser'
# Stopped / Running

$ServiceName = 'MSSQL$SQLEXPRESS'
if ((get-service $ServiceName).Status -eq 'Stopped') {
    # démarrer un service, nécessite les droits administrateur
    start-service $ServiceName -PassThru
    # PassThru force l'affichage d'un message de sortie
}
else {
    echo "$ServiceName est déjà démarré."
}

MessageBox

Powershell.svg
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Windows.Forms.MessageBox]::Show("Hello !")

Web

wget et iwr sont des alias de Invoke-WebRequest
Powershell.svg
# get the content and detect the output format: XML or JSON
Invoke-RestMethod http://www.domain.net/api/values | % { $_ | select Prop1, Prop2 | Out-GridView }

Invoke-RestMethod http://localhost:111/api/values -Method POST -Body @{value='2'}

Invoke-WebRequest http://localhost:111/api/values -H @{"accept"="application/xml"} | Select-Object -Expand Content

$content = (New-Object Net.WebClient).DownloadString("http://www.google.fr")

wget http://www.domain.net/file.txt -outfile folder\file.txt

Target HTML

Ps.svg
$url = "http://www.domain.net"
$result = Invoke-WebRequest $url

$result.AllElements |
    Where Class -eq "some css class" |
    Select -First 1 -ExpandProperty innerText

Registre

Powershell.svg
$RegKey ="HKCU:\Control Panel\Cursors"
# Obtenir la valeur de la clé IBeam
Get-ItemProperty -Path "HKCU:\Control Panel\Cursors" | select -ExpandProperty IBeam
# Changement de la valeur de la clé IBeam
Set-ItemProperty -Path $RegKey -Name IBeam -Value "%SystemRoot%\cursors\beam_r.cur"

Use C# code

Ps.svg
Add-Type -TypeDefinition @"
public class Compute {
    public int Add(int n1, int n2) {
        return n1 + n2;
    }
}
"@

# load an assembly
Add-Type -Path C:\Folder\Compute.dll

$compute = New-Object Compute
$compute.Add(6, 4)  # 10

Exemples

Recherche de texte dans tous les fichiers - rg - ripgrep

Powershell.svg
Function rg {
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]
        $pattern
    )
    ls -r | sls $pattern -context 2 |
		foreach {
			"{0} : {1:00}" -f $_.Path, $_.LineNumber
			if ($_.Context.PreContext) {"  {0}" -f $_.Context.PreContext }
			"> {0}" -f $_.Line
			if ($_.Context.PostContext) { "  {0}" -f $_.Context.PostContext }
			""
		} 
}

Stocker et récupérer un mot de passe

Powershell.svg
# store password
$Password = "Password123!@#"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force  # SecureString
# ou demande du password
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
# ou demande du password avec Get-Credential
$Credential = Get-Credential -Message "Enter password" -Username "-"
$SecurePassword = $Credential.Password
$SecureStringAsPlainText = $SecurePassword | ConvertFrom-SecureString  # String
Set-Content "C:\Dossier\Password.txt" $SecureStringAsPlainText

# get the password
$SecureStringAsPlainText = Get-Content "C:\Dossier\Password.txt"  # String
$SecurePassword = $SecureStringAsPlainText | ConvertTo-SecureString  # SecureString
$Credential = New-Object PSCredential "user",$SecurePassword
$PlainPassword = $Credential.GetNetworkCredential().Password  # password en clair

Modifier le pointeur de la sourie

Powershell.svg
# changement du pointeur Text Selection
$RegKey ="HKCU:\Control Panel\Cursors"
Set-ItemProperty -Path $RegKey -Name IBeam -Value "%SystemRoot%\cursors\beam_r.cur"

# Rafraichissement des curseurs pour prendre en compte le changement
$CSharpSig = @'
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(
  uint uiAction,
  uint uiParam,
  uint pvParam,
  uint fWinIni);
'@

$CursorRefresh = Add-Type -MemberDefinition $CSharpSig -Name WinAPICall -Namespace SystemParamInfo –PassThru

$CursorRefresh::SystemParametersInfo(0x0057,0,$null,0)

SHA1

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

Windows API

Set Wallpaper

Ps.svg
# C# wrapper around Windows API SystemParametersInfo
Add-Type -TypeDefinition @"
using System.Runtime.InteropServices;

namespace WinAPI {
    public class DesktopWallpaper
    {
        public const int SetDesktopWallpaper = 0x14;
        public const int UpdateIniFile = 0x01;
        public const int SendWinIniChange = 0x02;
    
        [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] 
        public static extern int SystemParametersInfo (int uAction, 
                                                       int uParam, 
                                                       string lpvParam, 
                                                       int fuWinIni);
                                                       
        public static void SetWallpaper(string path)
        {
            SystemParametersInfo(SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange);
        }
    }
}
"@

[WinAPI.DesktopWallpaper]::SetWallpaper('C:\image.jpg')

Équivalents bash

find

Ps.svg
# find . -type f -iname "filename"
Get-ChildItem -Filter "*filename*" -Recurse -File
ls -r -file *filename*

sed

File encoding is changed to UTF-8 without BOM
Ps.svg
# sed 's/txt_to_replace/replacement_text/' -i file.txt
(Get-Content file.txt) -replace 'txt_to_replace', 'replacement_text' | Set-Content file.txt
(Get-Content file.txt) -replace '^(group1).*(group2)$', '$1 text $2' | Set-Content file.txt

grep

Ps.svg
# ls | grep *.txt
ls | % fullname | findstr -i "\.txt\>"
# -i  Ignores the case of the characters when searching for the string
# -v  Prints only lines that do not contain a match

# transforme la sortie objets en stream pour y faire une recherche
ls | out-string -stream | sls "\.txt"

which

Powershell.svg
(Get-Command notepad).Source
# C:\WINDOWS\system32\notepad.exe

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