Set-content

De wiki.nexiat.fr
Aller à la navigation Aller à la recherche
Fiche express
Cmdlet Set-Content
Rôle Écrire du contenu dans un fichier
Voir aussi Read-host

Set-Content écrit ou remplace le contenu d'un fichier (ou d'un composant supportant l'écriture).

Usage

Get-Process powershell | Out-File fichier.txt

# Transtypage via une chaîne
Get-Process powershell | Out-String -Stream | Set-Content fichier.txt

# Écrire au format octets
Set-Content -Encoding Byte

Options

-Path <string[]>          fichier(s) cible(s)
-Value <Object[]>         contenu à écrire (remplace l'existant)
-Include <string[]>       modifie uniquement les objets spécifiés
-Exclude <string[]>       omet certains objets
-Filter <string>          filtre selon le fournisseur
-PassThru                 renvoie l'objet écrit dans le pipe
-Force                    crée le répertoire au besoin
-Credential <PSCredential>
-Encoding <String>        format d'encodage

Créer un fichier binaire

# Le cas générique ajoute des retours chariot CR/LF
'AABB' | Set-Content fichier.txt

# Sans retour : conversion en chaîne de caractères puis en octets
[byte[]][char[]]'AABB' | Set-Content fichier.txt -Encoding Byte

Convertir un fichier Unix (LF) en DOS (CRLF) :

param ($path = $(throw 'fichier non trouvé'), $dest = $path)

$tab = Get-Content $path -Encoding Byte
for ($i = 0; $i -lt $tab.Length; $i++) {
    if ($tab[$i] -eq 10) {
        $tab = $tab[0..$($i-1)] + [byte]13 + $tab[$i..$tab.Length]
        $i++
    }
}
$tab | Set-Content $dest -Encoding Byte

Voir aussi