« PowerShell » : différence entre les versions

Aller à la navigation Aller à la recherche
 
(54 versions intermédiaires par le même utilisateur non affichées)
Ligne 1 : Ligne 1 :
{{Sommaire}}
'''PowerShell''' est un langage de programmation pour les systèmes Microsoft Windows.
'''PowerShell''' est un langage de programmation pour les systèmes Microsoft Windows.


== Référence ==
== Référence ==
=== IT-Connect ===
* http://www.it-connect.fr/powershell-pour-les-debutants-1ere-partie/
* http://www.it-connect.fr/powershell-pour-les-debutants-1ere-partie/
* http://www.it-connect.fr/powershell-et-active-directory-modifier-le-domaine-des-adresses-mails/
* http://www.it-connect.fr/powershell-et-active-directory-modifier-le-domaine-des-adresses-mails/
Ligne 7 : Ligne 11 :
* http://www.it-connect.fr/creer-des-comptes-utilisateurs-par-lot-avec-powershell-v2-et-le-module-active-directory-server-2008-r2/
* http://www.it-connect.fr/creer-des-comptes-utilisateurs-par-lot-avec-powershell-v2-et-le-module-active-directory-server-2008-r2/
* http://www.it-connect.fr/chapitres/modifier-la-resolution-de-lecran/
* http://www.it-connect.fr/chapitres/modifier-la-resolution-de-lecran/
----
 
Convention de nommage (charte de nommage) pour ses serveurs :
* https://www.it-connect.fr/quelle-convention-de-nommage-utiliser-pour-ses-serveurs/
 
=== Marie Pascal Delamare ===
Site de Marie Pascal Delamare, BTS SIO / STS SIO
Site de Marie Pascal Delamare, BTS SIO / STS SIO
* http://mariepascal.delamare.free.fr/
* http://mariepascal.delamare.free.fr/
=== Youtube ===
John Savill's Technical Training, chaîne Youtube
* https://www.youtube.com/@NTFAQGuy
* série de vidéos sur PowerShell :
** https://www.youtube.com/watch?v=sQm4zRvvX58&list=PLlVtbbG169nFq_hR7FcMYg32xsSAObuq8
TechSnips by ATA Learning, chaine Youtube, sélection "Doing anything with PowerShell", 334 vidéos au 29/05/2023 :
* https://www.youtube.com/playlist?list=PLviQuRV5ySnzt8YpB14SfHeJm8Rh0oO1A
TechThoughts, chaine Youtube, 41 vidéos au 11/06/2023 :
* https://www.youtube.com/@Techthoughts2/videos
* série de vidéos sur PowerShell :
** Learn PowerShell, https://www.youtube.com/watch?v=csuz7qSJv_Q&list=PL2j0_s2VJe2hzQuQyn6yfMS2olhhs4UnQ
CyberAutomate :
* https://www.youtube.com/@CyberAutomate/videos


== Document ==
== Document ==
Ligne 32 : Ligne 57 :
** source : https://cnf1g.com/powershell-creer-de-petites-applications-graphiques-gui/
** source : https://cnf1g.com/powershell-creer-de-petites-applications-graphiques-gui/
** [[Powershell/Generated Form Function]]
** [[Powershell/Generated Form Function]]
== Exemple ==


== Windows10Debloater ==
== Windows10Debloater ==
* https://github.com/Sycnex/Windows10Debloater
* https://github.com/Sycnex/Windows10Debloater


== Script de nettoyage de fichier ==
== Script si problème mise à jour Windows ==
<pre>
Le service "Windows Update" s'appelle <code>wuauserv</code> :
# Traitement de texte sur fichier brut (enlever les lignes qui contiennent les mots ou expressions indiquées) ; le nouveau fichier est <code>fichier2.txt</code>
* <source inline>Stop-Service -Name wuauserv</source>
# l'expression "^[?]" indique une ligne commençant par un point d'interrogation.
* <source inline>Start-Service -Name wuauserv</source>
# la barre verticale sépare les expressions recherchées ; les espaces sont pris en compte.
* <source inline>Set-Service -Name wuauserv -StartupType Automatic</source>
$fichier = get-content "c:\tmp\scores.txt" | where {$_ -notmatch "^[?]|putain|bite|caca| cul| chauve| mere"}
* <source inline>Set-Service -Name wuauserv -StartupType Manual</source>
set-content fichier2.txt $fichier
* <source inline>Set-Service -Name wuauserv -StartupType Disabled</source>
</pre>


==== Fenêtre de dialogue ====
== Impression ==  
[[File:powershell-formulaire-01.png|vignette]]
Supprimer toutes les fichiers des files d'attente d'impression :
Création de fenêtre de dialogue :
<source>
* https://docs.microsoft.com/fr-fr/powershell/scripting/samples/creating-a-custom-input-box?view=powershell-6
Stop-Service Spooler
Remove-Item "C:\Windows\System32\spool\PRINTERS\*.*" -Force
Start-Service Spooler
</source>


=== Fenêtre de dialogue et sélection multiple ===
== Autre ==
<pre># Original example posted at http://technet.microsoft.com/en-us/library/ff730950.aspx


Add-Type -AssemblyName System.Windows.Forms
=== Logiciel menu ===
Add-Type -AssemblyName System.Drawing
<source>#################### - VARIABLES - ####################
$logiciel = @(
  [pscustomobject]@{nom="7Zip";          path="C:\Support\7zip\7z2201-x64.exe"}
  [pscustomobject]@{nom="VLC";            path="C:\Support\VLC\vlc-3.0.17.4-win64.exe"}
  [pscustomobject]@{nom="Adobe";          path="C:\Support\AdobeXI\AcroRdrDC2101120039_fr_FR.exe"}
  [pscustomobject]@{nom="BgInfo";        path="C:\Support\BgInfo\setup-BGInfo4.27.exe"}
  [pscustomobject]@{nom="Bureau distant"; path="C:\Support\Bureau distant\setup-bureau distant-v202211.exe"}
  )


# Fonction pour la création de boite de message
Clear-Host
function Show-Message {
    param (
        [string]$Message = "Veuillez entrer votre message",
        [string]$Titre = "Titre de la fenêtre",
        [switch]$OKCancel,
        [switch]$AbortRetryIgnore,
        [switch]$YesNoCancel,
        [switch]$YesNo,
        [switch]$RetryCancel,
        [switch]$IconErreur,
        [switch]$IconQuestion,
        [switch]$IconAvertissement,
        [switch]$IconInformation
        )


    # Affecter la valeur selon le type de boutons choisis
#################### - SCRIPT - #################### 
    if ($OKCancel) { $Btn = 1 }
$continue = $true
    elseif ($AbortRetryIgnore) { $Btn = 2 }
While ($continue) {
    elseif ($YesNoCancel) { $Btn = 3 }
  Write-Host "-------------------- Logiciel --------------------" -ForegroundColor Cyan
    elseif ($YesNo) { $Btn = 4 }
  Write-Host "> 1 --->" $logiciel[0].nom -ForegroundColor Cyan
     elseif ($RetryCancel) { $Btn = 5 }
  Write-Host "> 2 --->" $logiciel[1].nom -ForegroundColor Cyan
    else { $Btn = 0 }
  Write-Host "> 3 --->" $logiciel[2].nom -ForegroundColor Cyan
  Write-Host "> 4 --->" $logiciel[3].nom -ForegroundColor Cyan
  Write-Host "> 5 --->" $logiciel[4].nom -ForegroundColor Cyan
  Write-Host "> Tout ---> Installation de tous les logiciels de la liste" -ForegroundColor Cyan
  Write-Host "--------------------------------------------------" -ForegroundColor Cyan
  Write-Host "Sélectionner une option ou un type" -NoNewline
  Write-Host " [fin] " -ForegroundColor Yellow -NoNewline
  Write-Host "pour sortir : " -NoNewline
  $choix = Read-Host
     Switch ($choix) {
        "1" {
            try {
                Write-Host "Installation de"$logiciel[0].nom"sur le poste"
                Start-Process -FilePath $logiciel[0].path -ArgumentList "/S" -NoNewWindow -Wait
                }


    # Affecter la valeur pour l'icone
            catch {
    if ($IconErreur) {$Icon = 16 }
                Clear-Host
    elseif ($IconQuestion) {$Icon = 32 }
                Write-Warning "L'installation n'a pas pu se faire !"
    elseif ($IconAvertissement) {$Icon = 48 }
                }
    elseif ($IconInformation) {$Icon = 64 }
            }
    else {$Icon = 0 }
   
    # Charger la biblithèque d'objets graphiques Windows.Forms
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null


    # Afficher la boite de dialogue et renvoyer la valeur de retour (bouton appuyé)
      "2" {
    $Reponse = [System.Windows.Forms.MessageBox]::Show($Message, $Titre , $Btn, $Icon)
          Write-Host "Installation de"$logiciel[1].nom"sur le poste"
    Return $Reponse
          Start-Process -FilePath $logiciel[1].path -ArgumentList "/S" -NoNewWindow -Wait
    }
          }
    # Fin de la fonction pour la création de boite de message


# Création de la fenêtre de dialogue
      "3" {
$hauteurfenetre = 250
          Write-Host "Installation de"$logiciel[2].nom"sur le poste"
$form = New-Object System.Windows.Forms.Form
          Start-Process -FilePath $logiciel[2].path -ArgumentList "/S" -NoNewWindow -Wait
$form.Text = "Profils à supprimer"
          }
$form.Size = New-Object System.Drawing.Size(320,$hauteurfenetre)
$form.StartPosition = "CenterScreen"


$OKButton = New-Object System.Windows.Forms.Button
      "4" {
$OKButton.Location = New-Object System.Drawing.Point(75,($hauteurfenetre-80))
          Write-Host "Installation de"$logiciel[3].nom"sur le poste"
$OKButton.Size = New-Object System.Drawing.Size(75,23)
          Start-Process -FilePath $logiciel[3].path -ArgumentList "/S" -NoNewWindow -Wait
$OKButton.Text = "OK"
          }
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)


$CancelButton = New-Object System.Windows.Forms.Button
      "5" {
$CancelButton.Location = New-Object System.Drawing.Point(150,($hauteurfenetre-80))
          Write-Host "Installation de"$logiciel[4].nom"sur le poste"
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
          Start-Process -FilePath $logiciel[4].path -ArgumentList "/S" -NoNewWindow -Wait
$CancelButton.Text = "Cancel"
          }
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)


$label = New-Object System.Windows.Forms.Label
      "all" {
$label.Location = New-Object System.Drawing.Point(10,20)
          Write-Host "Installation de"$logiciel[0,1,2,3,4].nom"sur le poste"
$label.Size = New-Object System.Drawing.Size(280,20)
          Start-Process -FilePath $logiciel[0,1,2,3,4].path -ArgumentList "/S" -NoNewWindow -Wait
$label.Text = "Sélectionner les profils à supprimer ; sélection multiple"
          }
$form.Controls.Add($label)


$listBox = New-Object System.Windows.Forms.Listbox
      "fin" {
$listBox.Location = New-Object System.Drawing.Point(10,40)
          $continue = $false
$listBox.Size = New-Object System.Drawing.Size(280,($hauteurfenetre-120))
          }


$listBox.SelectionMode = "MultiExtended"
    default {  
 
        Clear-Host
## Exemple pour la suppression de profil local # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
         Write-Warning "Choix invalide"
# $profileliste = Get-WmiObject -ClassName Win32_UserProfile | Where-Object {$_.special -ne "true"} | foreach localpath
#
# foreach ($profile in $profileliste) {
# $listBox.Items.Add($profile)
# }
## à compléter...
 
## Exemple pour la suppression de dossier # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
$dossierliste = Get-childitem "c:\"
 
foreach ($dossier in $dossierliste) {
$listBox.Items.Add($dossier)
}
 
$form.Controls.Add($listBox)
$form.Topmost = $True
 
$result = $form.ShowDialog()
 
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    $x = $listBox.SelectedItems
    if ($x.count -eq 0) {
         $reponse = show-Message -Message "Aucun élément de sélectionné !" -Titre "Sélection" -IconAvertissement
         }
         }
    else {
  }
        $maliste = $x -join "`n"
}
        # $x
</source>
        $reponse = show-Message -Message "Confirmez-vous la suppression des éléments ci-dessous ?`n`n$maliste" -Titre "Confirmation" -YesNo -IconQuestion
        if ($reponse -eq "Yes") {
            foreach ($elem in $x) {
                Get-ChildItem "c:\$elem"
                }
            }
        else {
            $reponse = show-Message -Message "Suppression annulée !" -Titre "Annulation" -IconAvertissement
            }
        }
    }
</pre>
 
==== Image et redimensionnement ====
PowerShell et fonction :
* https://gist.github.com/someshinyobject/617bf00556bc43af87cd


[[Catégorie:PowerShell]]
== Voir aussi ==
[[Catégorie:Script]]
* &nbsp;

Dernière version du 16 novembre 2023 à 00:09

PowerShell est un langage de programmation pour les systèmes Microsoft Windows.

Référence

IT-Connect

Convention de nommage (charte de nommage) pour ses serveurs :

Marie Pascal Delamare

Site de Marie Pascal Delamare, BTS SIO / STS SIO

Youtube

John Savill's Technical Training, chaîne Youtube

TechSnips by ATA Learning, chaine Youtube, sélection "Doing anything with PowerShell", 334 vidéos au 29/05/2023 :

TechThoughts, chaine Youtube, 41 vidéos au 11/06/2023 :

CyberAutomate :

Document

Gestion des path sous PowerShell, PDF, 31 pages :

Source de script

Gérer les autorisations NTFS avec PowerShell :

Copie de fichiers avec BITS (Background Intelligent Transfer Service) :

PowerShell : convertir PS1 en EXE ; création d'un exécutable :

Interface graphique

Windows10Debloater

Script si problème mise à jour Windows

Le service "Windows Update" s'appelle wuauserv :

  • Stop-Service -Name wuauserv
  • Start-Service -Name wuauserv
  • Set-Service -Name wuauserv -StartupType Automatic
  • Set-Service -Name wuauserv -StartupType Manual
  • Set-Service -Name wuauserv -StartupType Disabled

Impression

Supprimer toutes les fichiers des files d'attente d'impression :

Stop-Service Spooler 
Remove-Item "C:\Windows\System32\spool\PRINTERS\*.*" -Force 
Start-Service Spooler

Autre

Logiciel menu

#################### - VARIABLES - ####################
$logiciel = @(
   [pscustomobject]@{nom="7Zip";           path="C:\Support\7zip\7z2201-x64.exe"}
   [pscustomobject]@{nom="VLC";            path="C:\Support\VLC\vlc-3.0.17.4-win64.exe"}
   [pscustomobject]@{nom="Adobe";          path="C:\Support\AdobeXI\AcroRdrDC2101120039_fr_FR.exe"}
   [pscustomobject]@{nom="BgInfo";         path="C:\Support\BgInfo\setup-BGInfo4.27.exe"}
   [pscustomobject]@{nom="Bureau distant"; path="C:\Support\Bureau distant\setup-bureau distant-v202211.exe"}
   )

Clear-Host

#################### - SCRIPT - ####################  
$continue = $true
While ($continue) {
   Write-Host "-------------------- Logiciel --------------------" -ForegroundColor Cyan
   Write-Host "> 1 --->" $logiciel[0].nom -ForegroundColor Cyan
   Write-Host "> 2 --->" $logiciel[1].nom -ForegroundColor Cyan
   Write-Host "> 3 --->" $logiciel[2].nom -ForegroundColor Cyan
   Write-Host "> 4 --->" $logiciel[3].nom -ForegroundColor Cyan
   Write-Host "> 5 --->" $logiciel[4].nom -ForegroundColor Cyan
   Write-Host "> Tout ---> Installation de tous les logiciels de la liste" -ForegroundColor Cyan
   Write-Host "--------------------------------------------------" -ForegroundColor Cyan
   Write-Host "Sélectionner une option ou un type" -NoNewline
   Write-Host " [fin] " -ForegroundColor Yellow -NoNewline
   Write-Host "pour sortir : " -NoNewline
   $choix = Read-Host
    Switch ($choix) {
        "1" {
            try {
                Write-Host "Installation de"$logiciel[0].nom"sur le poste"
                Start-Process -FilePath $logiciel[0].path -ArgumentList "/S" -NoNewWindow -Wait
                }

            catch {
                Clear-Host
                Write-Warning "L'installation n'a pas pu se faire !"
                }
            }

       "2" {
          Write-Host "Installation de"$logiciel[1].nom"sur le poste"
          Start-Process -FilePath $logiciel[1].path -ArgumentList "/S" -NoNewWindow -Wait
          }

       "3" {
          Write-Host "Installation de"$logiciel[2].nom"sur le poste"
          Start-Process -FilePath $logiciel[2].path -ArgumentList "/S" -NoNewWindow -Wait
          }

       "4" {
          Write-Host "Installation de"$logiciel[3].nom"sur le poste"
          Start-Process -FilePath $logiciel[3].path -ArgumentList "/S" -NoNewWindow -Wait
          }

       "5" {
          Write-Host "Installation de"$logiciel[4].nom"sur le poste"
          Start-Process -FilePath $logiciel[4].path -ArgumentList "/S" -NoNewWindow -Wait
          }

       "all" {
          Write-Host "Installation de"$logiciel[0,1,2,3,4].nom"sur le poste"
          Start-Process -FilePath $logiciel[0,1,2,3,4].path -ArgumentList "/S" -NoNewWindow -Wait
          }

       "fin" {
          $continue = $false
          }

    default { 
        Clear-Host 
        Write-Warning "Choix invalide"
        }
  }
}

Voir aussi

  •