Aller au contenu

Feuille de chaleur PowerShell

Aperçu général

PowerShell est une solution d'automatisation de tâches multiplateforme composée d'un shell en ligne de commande, d'un langage de script et d'un cadre de gestion de configuration.

Commandes de base

Aide

# Get help for a command
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Help Get-Process -Full

# Update help files
Update-Help

# Get command syntax
Get-Command Get-Process -Syntax
# Current location
Get-Location
pwd

# Change directory
Set-Location C:\Windows
cd C:\Windows

# List directory contents
Get-ChildItem
ls
dir

# Go back to previous directory
cd ..
```_

### Opérations de fichiers
```powershell
# Create new file
New-Item -ItemType File -Name "test.txt"
ni test.txt -ItemType File

# Create new directory
New-Item -ItemType Directory -Name "TestFolder"
mkdir TestFolder

# Copy files
Copy-Item source.txt destination.txt
cp source.txt destination.txt

# Move files
Move-Item oldname.txt newname.txt
mv oldname.txt newname.txt

# Remove files
Remove-Item test.txt
rm test.txt

# Get file content
Get-Content file.txt
cat file.txt

# Set file content
Set-Content -Path file.txt -Value "Hello World"
"Hello World"|Out-File file.txt
```_

## Variables et types de données

### Variables
```powershell
# Declare variables
$name = "John"
$age = 30
$isActive = $true

# Array
$colors = @("red", "green", "blue")
$numbers = 1,2,3,4,5

# Hash table
$person = @\\\\{
    Name = "John"
    Age = 30
    City = "New York"
\\\\}

# Access hash table values
$person.Name
$person["Age"]

Types de données

# String
$text = "Hello World"
$multiline = @"
This is a
multi-line string
"@

# Numbers
$integer = 42
$decimal = 3.14

# Boolean
$isTrue = $true
$isFalse = $false

# Date
$today = Get-Date
$specificDate = [DateTime]"2023-12-25"

Structures de contrôle

Déclarations conditionnelles

# If statement
if ($age -gt 18) \\\\{
    Write-Host "Adult"
\\\\} elseif ($age -eq 18) \\\\{
    Write-Host "Just turned adult"
\\\\} else \\\\{
    Write-Host "Minor"
\\\\}

# Switch statement
switch ($day) \\\\{
    "Monday" \\\\{ "Start of work week" \\\\}
    "Friday" \\\\{ "TGIF!" \\\\}
    "Saturday" \\\\{ "Weekend!" \\\\}
    "Sunday" \\\\{ "Weekend!" \\\\}
    default \\\\{ "Regular day" \\\\}
\\\\}

Boucles

# For loop
for ($i = 1; $i -le 10; $i++) \\\\{
    Write-Host $i
\\\\}

# ForEach loop
$colors = @("red", "green", "blue")
foreach ($color in $colors) \\\\{
    Write-Host $color
\\\\}

# While loop
$i = 1
while ($i -le 5) \\\\{
    Write-Host $i
    $i++
\\\\}

# Do-While loop
do \\\\{
    $input = Read-Host "Enter 'quit' to exit"
\\\\} while ($input -ne "quit")

Fonctions

Fonctions de base

# Simple function
function Say-Hello \\\\{
    Write-Host "Hello World!"
\\\\}

# Function with parameters
function Say-HelloTo \\\\{
    param(
        [string]$Name
    )
    Write-Host "Hello, $Name!"
\\\\}

# Function with return value
function Add-Numbers \\\\{
    param(
        [int]$a,
        [int]$b
    )
    return $a + $b
\\\\}

# Call functions
Say-Hello
Say-HelloTo -Name "John"
$result = Add-Numbers -a 5 -b 3

Fonctions avancées

function Get-SystemInfo \\\\{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$ComputerName,

        [Parameter()]
        [switch]$IncludeServices
    )

    $info = Get-ComputerInfo -ComputerName $ComputerName

    if ($IncludeServices) \\\\{
        $services = Get-Service -ComputerName $ComputerName
        $info|Add-Member -NotePropertyName Services -NotePropertyValue $services
    \\\\}

    return $info
\\\\}

Pipelines et objets

Bases des pipelines

# Basic pipeline
Get-Process|Where-Object \\\\{$_.CPU -gt 100\\\\}|Sort-Object CPU -Descending

# Select specific properties
Get-Process|Select-Object Name, CPU, WorkingSet

# Format output
Get-Process|Format-Table Name, CPU, WorkingSet
Get-Process|Format-List Name, CPU, WorkingSet

Manipulation d'objets

# Create custom objects
$person = [PSCustomObject]@\\\\{
    Name = "John"
    Age = 30
    City = "New York"
\\\\}

# Add properties
$person|Add-Member -NotePropertyName Email -NotePropertyValue "john@email.com"

# Filter objects
Get-Process|Where-Object \\\\{$_.ProcessName -like "chrome*"\\\\}

# Group objects
Get-Process|Group-Object ProcessName

# Measure objects
Get-Process|Measure-Object WorkingSet -Sum -Average -Maximum

Traitement de fichiers et de textes

Opérations de fichiers

# Read file line by line
Get-Content file.txt|ForEach-Object \\\\{
    Write-Host "Line: $_"
\\\\}

# Search in files
Select-String -Path "*.txt" -Pattern "error"

# Replace text in files
(Get-Content file.txt) -replace "old", "new"|Set-Content file.txt

# Get file information
Get-ItemProperty file.txt
Get-ChildItem *.txt|Select-Object Name, Length, LastWriteTime

Traitement de texte

# String operations
$text = "Hello World"
$text.ToUpper()
$text.ToLower()
$text.Replace("World", "PowerShell")
$text.Split(" ")
$text.Substring(0, 5)

# Regular expressions
$text = "Phone: 123-456-7890"
if ($text -match "\d\\\\{3\\\\}-\d\\\\{3\\\\}-\d\\\\{4\\\\}") \\\\{
    Write-Host "Phone number found: $($matches[0])"
\\\\}

Administration du système

Gestion des processus

# Get processes
Get-Process
Get-Process -Name "notepad"
Get-Process|Where-Object \\\\{$_.CPU -gt 100\\\\}

# Start process
Start-Process notepad
Start-Process -FilePath "C:\Program Files\App\app.exe" -ArgumentList "/silent"

# Stop process
Stop-Process -Name "notepad"
Stop-Process -Id 1234

Gestion des services

# Get services
Get-Service
Get-Service -Name "Spooler"
Get-Service|Where-Object \\\\{$_.Status -eq "Running"\\\\}

# Start/Stop services
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "Spooler"

# Set service startup type
Set-Service -Name "Spooler" -StartupType Automatic

Opérations du Greffe

# Navigate registry
Set-Location HKLM:\SOFTWARE

# Get registry values
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"

# Set registry values
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting" -Value "Value"

# Create registry keys
New-Item -Path "HKCU:\Software\MyApp"

Opérations réseau

Commandes réseau

# Test network connectivity
Test-Connection google.com
Test-NetConnection google.com -Port 80

# Get network configuration
Get-NetIPConfiguration
Get-NetAdapter

# DNS operations
Resolve-DnsName google.com
Clear-DnsClientCache

Demandes Web

# Simple web request
Invoke-WebRequest -Uri "https://api.github.com/users/octocat"

# REST API calls
$response = Invoke-RestMethod -Uri "https://api.github.com/users/octocat"
$response.name

# Download files
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"

Gestion des erreurs

Essayez-enfin

try \\\\{
    $result = 10 / 0
\\\\} catch [System.DivideByZeroException] \\\\{
    Write-Host "Cannot divide by zero!"
\\\\} catch \\\\{
    Write-Host "An error occurred: $($_.Exception.Message)"
\\\\} finally \\\\{
    Write-Host "Cleanup code here"
\\\\}

Variables d'erreur

# Check last error
$Error[0]

# Clear errors
$Error.Clear()

# Error action preference
$ErrorActionPreference = "Stop"  # Stop, Continue, SilentlyContinue

Modules et Snap-ins

Gestion des modules

# List available modules
Get-Module -ListAvailable

# Import module
Import-Module ActiveDirectory

# Get module commands
Get-Command -Module ActiveDirectory

# Install module from PowerShell Gallery
Install-Module -Name Az

Création de modules

# Create module file (MyModule.psm1)
function Get-Greeting \\\\{
    param([string]$Name)
    return "Hello, $Name!"
\\\\}

Export-ModuleMember -Function Get-Greeting

# Import custom module
Import-Module .\MyModule.psm1

Scénario des meilleures pratiques

Structure des scripts

#Requires -Version 5.1
#Requires -Modules ActiveDirectory

<#
.SYNOPSIS
    Brief description of script
.DESCRIPTION
    Detailed description
.PARAMETER Name
    Description of parameter
.EXAMPLE
    Example usage
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [string]$Name
)

# Script logic here
Write-Verbose "Processing $Name"

Validation du paramètre

param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Name,

    [Parameter()]
    [ValidateRange(1,100)]
    [int]$Age,

    [Parameter()]
    [ValidateSet("Red","Green","Blue")]
    [string]$Color
)

Caractéristiques avancées

Emploi

# Start background job
$job = Start-Job -ScriptBlock \\\\{ Get-Process \\\\}

# Get job status
Get-Job

# Receive job results
Receive-Job $job

# Remove job
Remove-Job $job

Suppression

# Enable remoting
Enable-PSRemoting -Force

# Create session
$session = New-PSSession -ComputerName "Server01"

# Run commands remotely
Invoke-Command -Session $session -ScriptBlock \\\\{ Get-Process \\\\}

# Enter interactive session
Enter-PSSession -Session $session

# Close session
Remove-PSSession $session

Configuration de l'état désiré (DSC)

Configuration WebServer \\\\{
    Node "WebServer01" \\\\{
        WindowsFeature IIS \\\\{
            Ensure = "Present"
            Name = "Web-Server"
        \\\\}

        File WebContent \\\\{
            Ensure = "Present"
            DestinationPath = "C:\inetpub\wwwroot\index.html"
            Contents = "<html><body>Hello World</body></html>"
        \\\\}
    \\\\}
\\\\}

# Compile configuration
WebServer -OutputPath "C:\DSC"

# Apply configuration
Start-DscConfiguration -Path "C:\DSC" -Wait -Verbose

Opérateurs communs

Opérateurs de comparaison

-eq    # Equal
-ne    # Not equal
-gt    # Greater than
-ge    # Greater than or equal
-lt    # Less than
-le    # Less than or equal
-like  # Wildcard comparison
-match # Regular expression match
-contains # Collection contains value
-in    # Value in collection

Opérateurs logiques

-and   # Logical AND
-or    # Logical OR
-not   # Logical NOT
!      # Logical NOT (alternative)

Cmdlets utiles

Collecte d'informations

Get-ComputerInfo
Get-HotFix
Get-EventLog -LogName System -Newest 10
Get-WmiObject -Class Win32_OperatingSystem
Get-CimInstance -ClassName Win32_ComputerSystem

Surveillance de la performance

Get-Counter "\Processor(_Total)\% Processor Time"
Get-Process|Sort-Object CPU -Descending|Select-Object -First 10
Measure-Command \\\\{ Get-Process \\\\}

Ressources

  • Documentation officielle: [Microsoft PowerShell Docs] (LINK_3)
  • PowerShell Gallery: [PowerShell Gallery] (LINK_3)
  • Communauté: Communauté PowerShell