FAQ POWERSHELL EN FRANÇAIS

By | March 7, 2015

 


Concept : La liste des questions les plus fréquentes sur Powershell.

Cette liste peut être utilisée de différentes manières :

  • Copier / coller les commandes dans un script
  • Identifier rapidement la syntaxe d’une commande
  • Améliorer vos connaissances techniques
  • Découvrir de nouvelles commandes
  • Se préparer pour un entretien d’embauche

Mise à jour
07 Octobre 2015
Auteur powershell-guru.com
Source french.powershell-guru.com
Catégories
75
Questions
610


ACL
Active Directory
Alias
Arrays
Browsers
Certificates
Characters
CIM
Comments
COM Objects
Compare
Computer
Credentials
CSV
Culture
Date
Drives
Environment
Errors
Event Viewer
Files
Folders
Format Operator (-f)
Functions
GPO
GUI
Hardware
Hashtables
Help
History
Jobs
Keyboard
Loops
Math
Memory
Messages
Modules
Microsoft Excel
Microsoft Exchange
Microsoft Outlook
Microsoft SharePoint
Networking
Openfiles
Operators
Parameters
Password
Powershell ISE
Powershell v5
Printers
Processes
PSObject
Quest
Random
RDP
Regedit
Regex
Remote
Restore
Scheduled Tasks
Search
SCCM
Services
SMTP
Snapins
Sounds
Static .NET Methods
Strings
System
Try/Catch
Variables
Symantec Vault
Windows 2012
Windows Azure
Windows Forms
WMI
XML

System

Comment déterminer ma version de Powershell ?

Comment faire pour exécuter Powershell dans une autre version pour la compatibilité avec les versions précédentes ?
powershell.exe -Version 2.0

Comment exiger une version minimale de Powershell (3.0 et supérieure) dans un script en PowerShell ?
#Requires -Version 3.0

Comment exiger des privilèges administrateur pour un script en Powershell ?

Comment vérifier les paramètres d’un script en Powershell ?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full

Comment afficher les informations de l’utilisateur actuel en Powershell ?
[Security.Principal.WindowsIdentity]::GetCurrent()

Comment créer, éditer et recharger un profil en Powershell?

Comment faire une pause de 5 secondes / minutes dans un script en Powershell ?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes

Comment afficher la date du dernier redémarrage (reboot) en Powershell ?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime

Comment afficher les types d’accélérateurs en Powershell ?

Comment afficher la liste des programmes de démarrage en Powershell ?

Comment désinstaller une application en Powershell ?

Comment faire une capture d’écran (screenshot) du bureau ou de la fenêtre en cours en Powershell ?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot

Comment compter le nombre de messages dans les files d’attente MSMQ en Powershell ?

Comment modifier la politique d’exécution des scripts en Powershell ?

Comment créer un raccourci en Powershell ?

Comment pingler ou dépingler un programme à la barre des tâches en Powershell ?

Comment lancer une fenêtre Explorer en Powershell ?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe

Comment afficher la liste des drivers en Powershell ?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe

Comment créer un GUID en Powershell ?

Comment afficher l’emplacement du répertoire temporaire de l’utilisateur actuel en Powershell ?
[System.IO.Path]::GetTempPath()

Comment joindre un chemin parent et un chemin enfant en un seul chemin en PowerShell?
Join-Path -Path C:\ -ChildPath \windows

Comment lister les cmdlets commençant par “Get-*” en Powershell ?
Get-Command -Verb Get

Comment afficher les dossiers système spéciaux en Powershell ?

Comment monter des fichiers ISO / VHD en Powershell ?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD

Comment vérifier les versions .NET Framework installées en Powershell ?

Comment vérifier si la version .NET Framework 4.5 est installée en Powershell ?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'

Comment démarrer et arrêter un transcript (pour enregistrer le contenu de la session Windows PowerShell) en Powershell ?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript

Comment changer le répertoire courant à un emplacement spécifique en Powershell ?
Set-Location -Path 'C:\scripts'

Comment effacer l’écran en Powershell ?
Clear-Host
cls # Alias

Comment changer la résolution d’écran en Powershell ?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012

Comment passer la fenêtre en plein écran en Powershell ?
mode.com 300

Comment obtenir les dimensions (largeur et hauteur) d’une image en Powershell ?

Comment obtenir la clé de produit Windows en PowerShell?

Perfmon

Comment faire pour obtenir le “% Temps processeur” (moyenne) dans les 5 dernières secondes (10 fois) en Powershell ?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue

Assemblies

Comment charger les assembleurs en Powershell ?

Comment vérifier les assembleurs .NET chargés en Powershell ?

Comment afficher le chemin GAC (Global Assembly Cache) en Powershell ?

Clipboard

Comment copier les résultats dans le presse-papiers (clipboard) en Powershell ?

Comment afficher le contenu du presse-papiers (clipboard) en Powershell ?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()

Hotfixes

Comment obtenir les correctifs installés en Powershell ?
Get-HotFix -ComputerName $computer

Comment obtenir les correctifs installés avant / après une date spécifique en Powershell ?
Get-HotFix | Where-Object -FilterScript { $_.InstalledOn -lt ([DateTime]'01/01/2015') } # Before 01/01/2015
Get-HotFix | Where-Object -FilterScript {$_.InstalledOn -gt ([DateTime]'01/01/2015')} # After 01/01/2015

Comment vérifier si un correctif est installé en Powershell ?
Get-HotFix -Id KB2965142

Comment obtenir les correctifs installés sur un ordinateur distant en Powershell ?
Get-HotFix -ComputerName $computer

Pagefile

Comment obtenir les informations du fichier de pagination (Pagefile) en Powershell ?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate

Comment obtenir la taille recommandée (MB) du fichier de pagination (Pagefile) en Powershell ?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5

Comment créer un fichier de pagination (4096 MB) sur le lecteur D: en Powershell ?

Comment supprimer un fichier de pagination sur le lecteur C: en Powershell ?

Maintenance

Comment vérifier la fragmentation d’un disque en Powershell ?

Comment vérifier l’espace des disques en Powershell ?

Up


Files

Comment ouvrir un fichier en Powershell ?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'

Comment lire un fichier en Powershell ?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias

Comment écrire la sortie dans un fichier en Powershell ?

Comment afficher l’emplacement du script en cours d’exécution en Powershell ?
$MyInvocation.MyCommand.Path

Comment compresser / zipper un fichier en Powershell ?

Comment décompresser / dézipper un fichier en Powershell ?

Comment afficher les fichiers d’une archive ZIP en Powershell ?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)

Comment afficher la taille d’un fichier en KB / MB / GB en Powershell ?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB

Comment trouver des fichiers de plus ou de moins de 1 Go en Powershell ?

Comment afficher le nom d’un fichier sans son extension en Powershell ?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc

Comment afficher l’extension d’un fichier en Powershell ?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt

Comment afficher la version d’un fichier en Powershell ?

Comment obtenir le hash d’un fichier en Powershell ?
(Get-FileHash $file).Hash

Comment obtenir le checksum MD5 / SHA1 d’un fichier en Powershell ?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1

Comment afficher les fichiers cachés en Powershell ?

Comment vérifier si un fichier a une extension en Powershell ?

Comment définir un fichier en “Lecture seule” (Read-Only) en Powershell ?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true

Comment changer l’attribut LastWriteTime à la date de la semaine dernière pour un fichier en Powershell ?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.

Comment créer un nouveau fichier en Powershell ?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'

Comment renommer un fichier en Powershell ?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'

Comment renommer en masse des fichiers en Powershell ?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }

Comment supprimer un fichier en Powershell ?
Remove-Item -Path 'C:\scripts\file.txt'

Comment afficher les 10 dernières lignes d’un fichier en Powershell ?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10

Comment débloquer plusieurs fichiers d’un dossier en Powershell ?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File

Comment supprimer les lignes vides d’un fichier en Powershell ?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt

Comment vérifier si un fichier existe en Powershell ?

Comment lister les fichiers les plus récents / anciens dans un dossier en Powershell ?

Comment supprimer les lignes dupliquées dans un fichier en Powershell ?

Comment lister les fichiers créés il y a plus / moins d’un mois en Powershell ?

Comment lister les fichiers créés il y a plus / moins d’un an en Powershell ?

Comment exporter la valeur d’une variable dans un fichier en Powershell ?
Set-Content -Path file.txt -Value $variable

Comment compter le nombre de fichiers (*.txt) dans un dossier en Powershell ?

Comment rechercher une chaîne de caractères dans plusieurs fichiers en PowerShell ?
Select-String -Path 'C:\*.txt' -Pattern 'Test'

Comment afficher la première / dernière ligne d’un fichier en PowerShell ?

Comment afficher un numéro de ligne spécifique d’un fichier en PowerShell ?

Comment compter le nombre de lignes d’un fichier en PowerShell ?

Comment compter le nombre de caractères et de mots d’un fichier en PowerShell ?

Comment télécharger un fichier en Powershell ?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'

Comment afficher l’emplacement complet d’un fichier en Powershell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1

Copy

Comment copier un fichier dans un dossier en Powershell ?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'

Comment copier un fichier dans plusieurs dossiers en PowerShell ?

Comment copier plusieurs fichiers dans un dossier en PowerShell ?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'

Up


Active Directory

Domain & Forest

Computers

Groups

Organizational Unit (OU)

Users

Domain & Forest

Comment afficher les serveurs de catalogue global dans Active Directory en Powershell ?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs

Comment afficher les sites Active Directory en Powershell ?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites

Comment afficher le contrôleur de domaine actuel dans Active Directory en Powershell ?

Comment afficher les contrôleurs de domaine d’un domaine Active Directory en Powershell ?

Comment afficher les problèmes de réplication Active Directory en Powershell ?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012

Comment afficher la durée de vie des objets supprimés (tombstonelifetime) dans Active Directory en Powershell ?

Comment afficher les détails de la forêt / domaine dans Active Directory en Powershell ?

Comment afficher l’emplacement du conteneur “Deleted Objects” dans Active Directory en Powershell ?
(Get-ADDomain).DeletedObjectsContainer

Comment activer la corbeille Active Directory en Powershell ?

Comment restaurer un objet supprimé dans Active Directory en Powershell ?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject

Comment afficher les rôles FSMO dans Active Directory en Powershell ?

Comment se connecter à un contrôleur de domaine spécifique en Powershell ?
Get-ADUser -Identity $user -Server 'serverDC01'

Comment obtenir le serveur de logon actuel (logonserver) en Powershell ?

Comment faire pour exécuter “gpupdate” sur un ordinateur en Powershell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012

Groups

Comment créer un nouveau groupe dans Active Directory en Powershell ?

Comment supprimer un groupe dans Active Directory en Powershell ?
Remove-ADGroup -Identity 'PowershellGuru'

Comment ajouter un utilisateur à un groupe dans Active Directory en Powershell ?
Add-ADGroupMember "Powershell Guru" -Members powershellguru

Comment supprimer un utilisateur d’un groupe dans Active Directory en Powershell ?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru

Comment afficher les groupes vides (sans membres) dans Active Directory en Powershell ?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}

Comment compter le nombre de groupes vides (sans membres) dans Active Directory en Powershell ?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count

Comment obtenir les membres d’un groupe dans Active Directory en Powershell ?

Comment obtenir les membres d’un groupe avec les membres récursifs dans Active Directory en Powershell ?

Comment compter le nombre de membres d’un groupe avec / sans les membres récursifs dans Active Directory en Powershell ?

Users

Comment utiliser un astérisque dans le filtre de “Get-ADUser” dans Active Directory en Powershell ?

Comment déplacer un utilisateur dans une OU (Organizational Unit) dans Active Directory en Powershell ?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'

Comment afficher les groupes d’un utilisateur (MemberOf nested) d’un utilisateur dans Active Directory en Powershell ?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"

Comment afficher le nom court des groupes d’un utilisateur dans Active Directory en Powershell ?
(Get-ADUser -Identity $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object

Comment renommer le Nom (FullName), Nom Complet (DisplayName), Prénom (FirstName) and nom de famille (LastName) d’un utilisateur dans Active Directory en Powershell ?

Comment modifier la description, le bureau (Office) et le numéro de téléphone (telephoneNumber) d’un utilisateur dans Active Directory en Powershell ?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'

Comment modifier la date d’expiration au “31/12/2015″ ou “Jamais” d’un utilisateur dans Active Directory en Powershell ?

Comment déverrouiller un compte utilisateur dans Active Directory en Powershell ?
Unlock-ADAccount $samAccountName

Comment activer / désactiver un compte utilisateur dans Active Directory en Powershell ?

Comment supprimer un compte utilisateur dans Active Directory en Powershell ?
Remove-ADUser $samAccountName

Comment réinitialiser le mot de passe pour un compte utilisateur dans Active Directory en Powershell ?

Comment réinitialiser le mot de passe pour plusieurs comptes utilisateurs dans Active Directory en Powershell ?

Comment afficher le propriétaire (Owner) d’un fichier dans Active Directory en Powershell ?

Comment afficher l’OU (Organizational Unit) d’un utilisateur dans Active Directory en Powershell ?
[regex]::match("$((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value

Comment afficher les comptes utilisateurs désactivés dans Active Directory en Powershell ?

Comment afficher les comptes utilisateurs expirés dans Active Directory en Powershell ?
Search-ADAccount -AccountExpired

Comment afficher les comptes utilisateurs verrouillés dans Active Directory en Powershell ?
Search-ADAccount -LockedOut

Comment afficher le SID d’un compte utilisateur dans Active Directory en Powershell ?
(Get-ADUser -Identity $user -Properties SID).SID.Value

Comment convertir un nom d’utilisateur en SID dans Active Directory en Powershell ?

Comment convertir un SID en nom d’utilisateur dans Active Directory en Powershell ?

Comment diviser (split) l’attribut Distinguished Name d’un utilisateur dans Active Directory en Powershell ?

Comment afficher la date de création / modification d’un compte utilisateur dans Active Directory en Powershell ?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated

Comment afficher les propriétés facultatives et obligatoires pour la classe “Utilisateur” dans Active Directory en Powershell ?

Comment obtenir le chemin LDAP d’un utilisateur dans Active Directory en Powershell ?

Comment changer l’attribut CN (Canonical Name) pour un utilisateur dans Active Directory en Powershell ?
Rename-ADObject $((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'

Comment obtenir l’unité d’organisation (OU) parent d’un utilisateur dans Active Directory en Powershell ?

Comment obtenir le propriétaire d’un utilisateur (qui a créé le compte) dans Active Directory en Powershell ?

Comment convertir l’attribut pwdLastSet pour un utilisateur dans Active Directory en Powershell ?

Computers

Comment tester le canal sécurisé entre l’ordinateur local et son domaine en Powershell ?
Test-ComputerSecureChannel

Comment réparer le canal sécurisé entre l’ordinateur local et son domaine en Powershell ?
Test-ComputerSecureChannel -Repair

Comment désactiver un compte d’ordinateur dans Active Directory en Powershell ?
Disable-ADAccount $computer

Comment trouver les ordinateurs ayant une version spécifique du système d’exploitation dans Active Directory en Powershell ?

Organizational Unit (OU)

Comment créer une unité d’organisation (OU) dans Active Directory en Powershell ?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'

Comment obtenir des détails sur une unité d’organisation (OU) dans Active Directory en Powershell ?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *

Comment changer la description d’une unité d’organisation (OU) dans Active Directory en Powershell ?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'

Comment activer / désactiver la protection contre les suppressions accidentelles d’une unité d’organisation (OU) dans Active Directory en Powershell ?

Comment activer la protection contre les suppressions accidentelles pour toutes les unités d’organisation (OU) dans Active Directory en Powershell ?

Comment supprimer une unité d’organisation (OU) protégée contre les suppressions accidentelles dans Active Directory en Powershell ?

Comment convertir un DistinguishedName de l’unité d’organisation (OU) à CanonicalName dans Active Directory en Powershell ?

Comment lister les unités d’organisation (OU) vides avec Powershell?

Comment obtenir le manager d’un groupe avec Powershell?
(Get-ADGroup $dn -Properties Managedby).Managedby

Up


Regex (Regular Expression)

Comment extraire l’adresse IP v4 (ex : 80.80.228.8) avec Regex en Powershell ?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value

Comment extraire l’adresse MAC (ex : C0-D9-62-39-61-2D) avec un séparateur “-” avec Regex en Powershell ?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value

Comment extraire l’adresse MAC (ex : C0:D9:62:39:61:2D) avec un séparateur “:” avec Regex en Powershell ?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value

Comment extraire une date (ex : 10/02/2015) avec Regex en Powershell ?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value

Comment extraire une URL (ex : www.powershell-guru.com) avec Regex en Powershell ?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value

Comment extraire un email (ex : user@domain.com) avec Regex en Powershell ?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value

Comment extraire “guru” dans l’exemple avec Regex en Powershell ?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value

Comment extraire “guru.com”dans l’exemple avec Regex en Powershell ?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value

Comment extraire “powershell-guru.com” dans l’exemple avec Regex en Powershell ?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value

Comment extraire “123” dans l’exemple avec Regex en Powershell ?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value

Comment extraire le signe dollar “$” dans l’exemple avec Regex en Powershell ?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value

Comment remplacer (*.com) par (*.fr) dans l’exemple avec Regex en Powershell ?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')

Comment échapper une chaîne de caractères avec Regex en Powershell ?
[regex]::Escape('\\server\share')

Up


Memory

Comment forcer un appel du garbage collector en Powershell ?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Comment afficher la taille de la RAM en GB en Powershell ?

Up


Date

Comment afficher la date actuelle en Powershell ?
Get-Date
[Datetime]::Now

Comment afficher la date dans différents formats en Powershell ?

Comment convertir une date (DateTime) en date (String) en Powershell ?

Comment convertir une date (String) en date (DateTime) en Powershell ?

Comment calculer la différence (nombre de jours, heures, minutes et secondes) entre deux dates en Powershell ?
(New-TimeSpan -Start $dateStart -End $dateEnd).Days
(New-TimeSpan -Start $dateStart -End $dateEnd).Hours
(New-TimeSpan -Start $dateStart -End $dateEnd).Minutes
(New-TimeSpan -Start $dateStart -End $dateEnd).Seconds

Comment comparer deux dates en Powershell ?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False

Comment trier un array de dates en tant que “Datetime” en Powershell ?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}

Comment démarrer et arrêter un chronomètre en Powershell ?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono

Comment afficher le jour de la semaine en Powershell ?
(Get-Date).DayOfWeek #Sunday

Comment afficher la date d’hier en Powershell ?
(Get-Date).AddDays(-1)

Comment afficher le nombre de jours dans un mois (Février 2015) en Powershell ?
[DateTime]::DaysInMonth(2015, 2)

Comment savoir si une année est bissextile en Powershell ?
[DateTime]::IsLeapYear(2015)

Comment afficher les fuseaux horaires en Powershell ?
[System.TimeZoneInfo]::GetSystemTimeZones()

Up


Networking

Comment encoder (au format ASCII) et décoder une URL en Powershell ?

Quels sont les équivalents de commandes de réseau natives en Powershell ?

Comment obtenir l’adresse IP en Powershell ?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012

Comment désactiver l’adresse IP v6 (IPv6) en Powershell ?

Comment valider une adresse IP v4 (IPv4) en Powershell ?
if([ipaddress]'10.0.0.1'){'validated'}

Comment afficher l’adresse IP externe en Powershell ?

Comment obtenir le nom d’hôte (hostname) à partir d’une adresse IP en Powershell ?
([System.Net.Dns]::GetHostEntry($IP)).Hostname

Comment obtenir l’adresse IP à partir du nom d’hôte (hostname) en Powershell ?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString

Comment obtenir le FQDN d’un nom d’hôte en Powershell ?
[System.Net.Dns]::GetHostByName($computer).HostName

Comment obtenir la configuration réseau (IP, sous-réseau, passerelle et DNS) en Powershell ?

Comment obtenir l’adresse MAC en Powershell ?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress

Comment pinguer un ordinateur en Powershell ?

Comment vérifier si un ordinateur est connecté à Internet en Powershell ?

Comment effectuer une recherche whois pour un site Web avec PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')

Comment obtenir des détails sur l’IP publique (Géolocalisation) en Powershell ?

Comment vérifier si un port est ouvert ou fermé en Powershell ?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135

Comment faire un tracert en Powershell ?
Test-NetConnection www.google.com -TraceRoute

Comment réparer le profil d’une connection réseau domestique en Powershell ?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private

Comment afficher les connexions TCP en cours en Powershell ?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012

Comment raccourcir une longue URL en une plus petite en Powershell ?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"

Comment faire pour obtenir les paramètres de proxy en Powershell ?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

DNS

Comment afficher le cache DNS local en Powershell ?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012

Comment effacer le cache DNS local en Powershell ?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012

Comment effacer le cache DNS local sur un ordinateur distant en Powershell ?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02

Comment afficher le fichier Hosts en Powershell ?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'

Up


Password

Comment générer un mot de passe aléatoire en Powershell ?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)

Comment changer le mot de passe de l’administrateur local sur un serveur distant en Powershell ?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()

Comment obtenir la date d’expiration d’un mot de passe d’un compte Active Directory en Powershell ?

Up


Printers

Comment lister les imprimantes sur un serveur spécifique en Powershell ?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer

Comment lister les ports sur un serveur spécifique en Powershell ?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer

Comment changer l’emplacement / commentaire d’une imprimante en Powershell ?

Comment purger (annuler toutes les tâches) pour une imprimante en Powershell ?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()

Comment imprimer une page de test pour une imprimante en Powershell ?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()

Comment obtenir les files d’attente d’impression pour des imprimantes en Powershell Comment installer les prérequis pour l’installation d’un serveur Exchange 2007?

Up


Regedit

Read

Comment lister les ruches de registre en Powershell ?
Get-ChildItem -Path Registry::

Comment obtenir des valeurs de registre et les types de valeur en Powershell?

Comment lire les sous-clés de clé de registre en Powershell ?

Comment lister les sous-clés de clés de registre et de manière récursive en Powershell ?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue

Comment chercher les sous-clés avec un nom spécifique en Powershell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue

Comment retourner seulement le nom des sous-clés de registre en Powershell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet

Comment afficher les valeurs de registre en Powershell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'

Comment lire une valeur de registre spécifique en Powershell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName

Comment lire une valeur de registre spécifique sur l’ordinateur distant en Powershell?

Write

Comment créer une nouvelle clé de registre en Powershell ?
New-Item -Path 'HKCU:\Software\MyApplication'

Comment créer une valeur de registre en Powershell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'

Comment modifier une valeur de registre existante en Powershell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'

Delete

Comment supprimer une valeur de registre en Powershell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'

Comment supprimer une clé de registre en Powershell ?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force

Test

Comment tester si une clé de registre existe en Powershell ?
Test-Path -Path 'HKCU:\Software\MyApplication'

Comment tester si une valeur de registre existe en Powershell ?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'

Up


Strings

Comment supprimer les caractères vides au début d’une chaîne de caractères en Powershell ?
$string = ' PowershellGuru'
$string = $string.TrimStart()

Comment supprimer les caractères vides à la fin d’une chaîne de caractères en Powershell ?
$string = 'PowershellGuru '
$string = $string.TrimEnd()

Comment supprimer les caractères vides (début et fin) d’une chaîne de caractères en Powershell ?
$string = ' PowershellGuru '
$string = $string.Trim()

Comment convertir une chaîne de caractères en majuscules en Powershell ?
$string = 'powershellguru'
$string = $string.ToUpper()

Comment convertir une chaîne de caractères en minuscules en Powershell ?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()

Comment sélectionner la sous-chaîne “Powershell” de “PowershellGuru” en Powershell ?
$string.Substring(0,10)

Comment sélectionner la sous-chaîne “Guru” de “PowershellGuru” en Powershell ?
$string.Substring(10)

Comment sélectionner le nombre “123” de “Powershell123Guru” en Powershell ?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value

Comment obtenir l’indice (zero-based) “Guru” de “PowershellGuru” en Powershell ?
$string.IndexOf('Guru') # 10

Comment vérifier si une chaîne de caractères est nulle ou vide en Powershell ?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)

Comment vérifier si une chaîne de caractères est nulle, vide ou contient des espaces en Powershell ?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)

Comment vérifier si une chaîne de caractères contient une lettre spécifique en Powershell ?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success

Comment obtenir la longueur d’une chaîne de caractères en Powershell ?
$string.Length

Comment concaténer 2 chaînes de caractères en Powershell ?

Comment vérifier la présence de crochets “[ ]” dans une chaîne de caractères en Powershell ?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several

Comment vérifier la présence de parenthèses “( )” dans une chaîne de caractères en Powershell ?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several

Comment vérifier la présence d’accolades “{ }” dans une chaîne de caractères en Powershell ?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several

Comment vérifier la présence des signes “< >” dans une chaîne de caractères en Powershell ?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several

Comment vérifier la présence de lettres minuscules (abc) dans une chaîne de caractères en Powershell ?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False

Comment vérifier la présence de lettres majuscules (ABC) dans une chaîne de caractères en Powershell ?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False

Comment vérifier la présence de “[p” (p en minuscule) dans une chaîne de caractères en Powershell ?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True

Comment vérifier la présence de “[P” (P en majuscule) dans une chaîne de caractères en Powershell ?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True

Comment remplacer une ligne par une autre en Powershell ?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b

Comment convertir une division en une chaîne de caractères (Pourcentage) in Powershell ?
(1/2).ToString('P')

Comment trier des chaînes de caractères contenant des nombres en Powershell ?

Comment sélectionner le dernier mot d’une phrase en Powershell ?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell

Comment trouver le mot le plus long d’une phrase en Powershell ?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell

Comment compter le nombre de fois qu’une chaîne de caractères est présente dans une phrase en Powershell ?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3

Comment copier chaque caractère d’une chaîne en un tableau de caractères avec Powershell?

Comment convertir la première lettre en majuscule d’une chaîne de caractères en Powershell?

Comment faire un padding (gauche ou droite) d’une chaîne de caractères en Powershell?

Comment coder et décoder une chaîne de caractères en Base64 en Powershell ?

Comment convertir un nombre en binaire et depuis binaire en Powershell?

Comment obtenir uniquement le dernier dossier parent d’un chemin en Powershell?

Comment retourner uniquement le dernier élément d’un chemin en Powershell?

Up


Math

Comment afficher les méthodes de la classe System.Math en Powershell ?
[System.Math] | Get-Member -Static -MemberType Method

Comment obtenir la valeur absolue d’un nombre en Powershell ?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5

Comment obtenir la valeur d’un angle dont le sinus est le nombre spécifié en Powershell ?
[Math]::ASin(1) #Returns 1,5707963267949

Comment obtenir le “ceiling” d’un nombre en Powershell ?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2

Comment obtenir le “floor” d’un nombre en Powershell ?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1

Comment obtenir le logarithme de base d’un nombre spécifié en Powershell ?
[Math]::Log(4) #Returns 1,38629436111989

Comment obtenir le logarithme 10 de base d’un nombre spécifié en Powershell ?
[Math]::Log10(4) #Returns 0,602059991327962

Comment obtenir le maximum de deux valeurs en Powershell ?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2

Comment obtenir le minimum de deux valeurs en Powershell ?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4

Comment obtenir la valeur d’un nombre à la puissance spécifiée en Powershell ?
[Math]::Pow(2,4) #Returns 16

Comment arrondir un nombre à la valeur la plus proche en Powershell ?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4

Comment obtenir la partie entière d’un nombre décimal en Powershell ?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3

Comment obtenir la racine carrée d’un nombre en Powershell ?
[Math]::Sqrt(16) #Returns 4

Comment obtenir la valeur de la constante PI en Powershell ?
[Math]::Pi #Returns 3,14159265358979

Comment obtenir la valeur de la constante e en Powershell ?
[Math]::E #Returns 2,71828182845905

Comment vérifier si un nombre est pair / impair en Powershell ?
[bool]($number%2)

Up


Hashtables

Comment créer une hashtable vide en Powershell ?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable

Comment créer une hashtable avec des éléments en Powershell ?

Comment créer une hashtable triée par clé/nom (ordered dictionary) avec des éléments en Powershell ?

Comment ajouter des éléments (paire “clé-valeur”) dans une hashtable en Powershell ?
$hashtable.Add('Key4', 'Value4')

Comment obtenir une valeur spécifique dans une hashtable en Powershell ?

Comment obtenir la valeur minimale dans une hashtable en Powershell ?

Comment obtenir la valeur maximale dans une hashtable en Powershell ?

Comment modifier des éléments dans une hashtable en Powershell ?
$hashtable.Set_Item('Key1', 'Value1Updated')

Comment supprimer des éléments dans une hashtable en Powershell ?
$hashtable.Remove('Key1')

Comment effacer une hashtable en Powershell ?
$hashtable.Clear()

Comment vérifier la présence d’une clé / valeur dans une hashtable en Powershell ?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')

Comment trier par clé / valeur dans une hashtable en Powershell ?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending

Up


Arrays

Comment créer un array vide en Powershell ?
$array = @()
$array = [System.Collections.ArrayList]@()

Comment créer un array avec des éléments en Powershell ?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c

Comment ajouter des éléments dans un array en Powershell ?
$array += 'D'
[void]$array.Add('D')

Comment modifier un élément dans un array en Powershell ?
$array[0] = 'Z' # 1st item[0]

Comment vérifier la taille d’un array en Powershell ?
$array = 'A', 'B', 'C'
$array.Length # Returns 3

Comment obtenir un élément / plusieurs / tous les éléments d’un array en Powershell ?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)

Comment supprimer des éléments vides dans un array en Powershell ?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C

Comment vérifier si un élément existe dans un array en Powershell ?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False

Comment obtenir l’index d’un élément dans un array en Powershell ?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0

Comment inverser l’ordre des éléments dans un array en Powershell ?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A

Comment générer un élément de manière aléatoire d’un array en Powershell ?
$array | Get-Random

Comment trier un array de manière croissante / décroissante en Powershell ?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A

Comment compter le nombre d’éléments dans un array en Powershell ?
$array.Count

Comment ajouter un array à un autre en Powershell ?
$array1