Table des matières

PowerShell

Entrées / Sorties


Entrée clavier : Read-Host

Read-Host [[-Prompt] <Object>] [-AsSecureString] [<CommonParameters>]
PS C:\> $age = read-host "Please enter your age:"
Please enter your age:      #on saisit 35
PS C:\> $age
35
PS C:\> $pwd_secure_string = read-host "Enter a Password:" -assecurestring
Enter a Password : ********        #on saisit un mot de passe qui apparaît en '*'
#(la valeur est stockée en tant qu'objet SecureString dans la variable $pwd_secure_string.)


Sortie vers l'écran : Write-Host

Write-Host [[-Object] <Object>] [-BackgroundColor {<colour>}] [-ForegroundColor {<colour>}] [-NoNewline] [-Separator <Object>] [<CommonParameters>]

PS C:\> write-host "no newline test " -nonewline
 
no newline test PS C:\>
PS C:\> write-host (2,4,6,8,10,12) -Separator ", +2= "
 
2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12
PS C:\> write-host "Red on white text." -ForegroundColor red -BackgroundColor white
 
Red on white text.


Sortie vers le flux d'erreur : Write-Error

Write-Error -ErrorRecord <ErrorRecord>

Write-Error [-Message] <string>

Write-Error -Exception <Exception>

Sortie vers un fichier

Crée un fichier contenant le résultat de la commande :

PS C:\> Dir | Out-File "C:\MonFichierDir.txt"

Ajoute la chaîne de caractère à la fin du fichier indiqué :

PS C:\> Add-Content -path "C:\Fichier_de_test.txt" -value "Test d'écriture"


Exporter / Importer en CSV

Paramètre Description
Path Chemin du fichier de destination
InputObject Accepte un objet comme entrée
Force Remplace le fichier si celu-ci existe déjà
Encoding Type d'encodage. Par défaut ASCII
NoTypeInformation Ne prend pas en compte l'en-tête
NoGlobber Ne pas écraser le fichier s'il existe
Paramètre Description
Path Chemin du fichier source

On liste le journal des événements applications, et enregistre les 100 premiers événements dans un fichier Event.csv.

Ecriture du fichier CSV

PS C:\> Get-EventLog application -newest 1000 | Sort-Object -property instanceid -Unique | Select-Object TimeGenerated, EntryType, Source, EventID, message | Export-csv C:\Temp\Event.csv -Delimiter ";" -NoTypeInformation -Encoding utf8

Lecture du fichier CSV

PS C:\> Import-csv C:\Temp\event.csv -Delimiter ";"

TimeGenerated : 05/07/2022 08:58:33
EntryType     : Information
Source        : edgeupdate
EventID       : 0
Message       : Service stopped.

TimeGenerated : 23/06/2022 14:10:31
EntryType     : Warning
Source        : Microsoft-Windows-WMI
EventID       : 63
Message       : Un fournisseur, DMWmiBridgeProv1, a été inscrit dans l’espace de noms Windows Management Instrumentation root\cimv2\mdm\dmmap, afin d’utiliser le compte LocalSystem. Ce 
                compte bénéficie de privilèges et le fournisseur peut provoquer une violation de sécurité s’il ne représente pas correctement les demandes utilisateur.

TimeGenerated : 04/07/2022 09:30:33
...