Question Suppression des SID Orphelins sur les dossiers NTFS

Plus d'informations
il y a 1 an 8 mois - il y a 1 an 8 mois #32535 par Bruce
Bonjour, voici le code, il permet de sélectionner dans un out-gridview avec multiples sélections les comptes orphelins à supprimer.
{code]
Clear-Host
# Création d'un tableau
$SID_Orph = @()
# Repertoire à scanner
$Path = "\\monserveur\data\public"

$PathFolders = Get-ChildItem -Path $Path -Directory # -Depth 1
try
{
    foreach ($folder in $PathFolders) 
    {
        $FullPath = $Path + "\" + $folder.Name
        $acl = Get-Acl -Path $FullPath
        foreach($acc in $acl.access ) 
        { 
            $value = $acc.IdentityReference.Value 
            if($value -match "S-1-5-*") 
            {             
                $SID_Orph += New-Object PSObject -Property @{ 
                Chemin = $FullPath
                Valeur = $value}
                Write-Host -ForegroundColor Red -BackgroundColor Yellow "SID orphelin:  $value  - Dossier: $FullPath"
            }
        }
    }
    $selection = $SID_Orph | Out-GridView -Title "Dossiers avec SID oprphelins" -OutputMode Multiple |sort -Property Chemin
    foreach ($sel in $selection) 
    {
        $seldir = $sel.chemin
        $acl = Get-Acl -Path $sel.chemin
        foreach($acc in $acl.access ) 
        { 
            $value = $acc.IdentityReference.Value 
            if($value -match $sel.Valeur) 
            { 
                $ACL.RemoveAccessRule($acc) | Out-Null
                Set-Acl -Path  $sel.chemin -AclObject $acl -ErrorAction Stop
                Write-Host "Suppression SID orphelin:  $value  - Dossier: $seldir"
            }
        }
    }
}
catch
{
    Write-Error $Error
}
Write-Host -ForegroundColor Green -BackgroundColor Black "FIN"
[/code]
Dernière édition: il y a 1 an 8 mois par Laurent Dardenne. Raison: balise code

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 8 mois - il y a 1 an 8 mois #32560 par Bruce
Bonjour,
Voici le script modifié pour être executé chaque mois par exemple par une tâche planifiée avec envoi d'un mail de rapport.
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force
Import-Module ActiveDirectory
Clear-Host
# ======================================================================================================
# Activation de Mode TEST: TRUE ou FALSE -> affiche les infos a l'ecran en mode test
$testing = $false
# ======================================================================================================
# envoi des fichiers de log
$sendlog = $true

# ======================================================================================================
# Parametres pour envoi de rapport par mail
$smtpServer="192.168.1.247" # IP de votre serveur de mail
$from = "Maintenance Serveurs<maintenance@masociete.com>" # adresse de l'expediteur du mail pour votre script
$adminEmailAddr = "hotline@masociete.com"
$testingEmailAddr = "moi@masociete.com"
$textEncoding = [System.Text.Encoding]::UTF8
$SendMail = $true
# ======================================================================================================
# VARIABLES FICHIERS
$Path = "\\monserveur\data\mondossierparent" #scan de tous les sous dossiers
$PathFolders = Get-ChildItem -Path $Path -Directory
$prefix = get-date -format yyyy-MM-dd-
# ======================================================================================================
# Corps du Mail 
$now = Get-Date -UFormat '%m-%d-%y %H:%M'
$body = "
     <p>Nettoyage des SID orphelins - Date: $now</br>
     <b>Répertoire source: $Path</b>
     </p>"

# ======================================================================================================
#Recupere le nom du script
$ScriptName = $MyInvocation.MyCommand.Name
#Chemin du répertoire contenant le script
$RepScript = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition) 

# Recupération des infos du domaine
$SearchBase = (Get-AdDomainController).defaultpartition  # Resultat: DC=votredomaine,DC=local
$domain = $SearchBase -Split "," | ? {$_ -like "DC=*"}   # Resultat: DC=votredomaine DC=local
$domain = $domain -join "." -replace ("DC=", "")         # Resultat: votredomaine.local
#Nom du serveur d'execution du script
$serveur = [system.environment]::MachineName

# ======================================================================================================
# Creation du fichier de log TXT
if ($sendlog -eq $true) 
{
    $logfile = $prefix +"Log_monserveur_sid.txt"
    $LogPath = "C:\Logs" +"\"+ $logfile
    If (-not (Test-Path $LogPath)) # Si le fichier log n'existe pas on le crée
    {
        try
        {
            New-Item -ItemType file $logpath -ErrorAction SilentlyContinue -Force
            ADD-content -path $logpath -value "Suppression des ACL orphelines dans les dossiers - Date: $now"
            ADD-content -path $logpath -value "Répertoire racine: $Path`r"
        }
        catch
        {
            Write-Host -ForegroundColor Red -BackgroundColor White "$Error création du fichier log $logpath"
        }
    }
}

# ======================================================================================================
# DEBUT DU SCRIPT
try
{
    $cpt = 0
    foreach ($folder in $PathFolders) 
    {
        $FullPath = $Path + "\" + $folder.Name
        $acl = Get-Acl -Path $FullPath
        foreach($acc in $acl.access ) 
        { 
            $value = $acc.IdentityReference.Value 
            if($value -match "S-1-5-*") 
            { 
                $ACL.RemoveAccessRule($acc) | Out-Null 
                Set-Acl -Path  $FullPath -AclObject $acl -ErrorAction Stop
                if ($testing -eq $true) {Write-Host -ForegroundColor Red -BackgroundColor Yellow "Suppression SID orphelin:  $value - Dossier: $FullPath"}
                if ($sendlog -eq $true) {ADD-content -path $logpath -value "Suppression SID orphelin: $value - Dossier: $FullPath"}
                $body+="<b>Suppression du SID orphelin:</b> $value - Dossier: $FullPath</br>"
                $cpt++
            }
        }
    }
    if ($cpt -eq 0)
    {
        if ($testing -eq $true) {Write-Host -ForegroundColor Yellow -BackgroundColor Blue "Aucun SID orphelin trouvé !"}
        ADD-content -path $logpath -value "Aucun SID orphelin trouvé !"
        $body+="
         <p><font color=""0000FF"">Aucun SID orphelin trouvé !</font><br>
         </p>"
    }

    $body+="
     <p>Serveur d'execution du script: <b>$serveur</b><br>
     Nom du script: <font color=""0000FF"">$ScriptName</font><br>
     Localisation du script: <font color=""0000FF"">$RepScript</font><br>
     <br><br>    
     L'équipe Support<br>
     hotline@masociete.com<br>
     https://monsiteweb.fr<br></p>"

     if ($testing -eq $true) 
    {
        $recipient = $testingEmailAddr
        $subject="TEST: Suppression des SID Orphelins: $Path"
    }else
    {
        $recipient = $adminEmailAddr
        $subject="TACHE AUTO - Suppression des SID Orphelins: $Path"
    }
    # Envoi du mail 
    if ($sendmail -eq $true)
    {
        Send-Mailmessage -smtpServer $smtpServer -from $from -to $recipient -subject $subject -body $body -bodyasHTML -Attachments "$logpath" -priority High -Encoding $textEncoding -ErrorAction Stop -ErrorVariable err
    }
}
catch
{
    Write-Host -ForegroundColor Red -BackgroundColor White "$Error"
}
if ($testing -eq $true) {Write-Host -ForegroundColor Green -BackgroundColor Black "FIN"}
Dernière édition: il y a 1 an 8 mois par Laurent Dardenne.

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.428 secondes
Propulsé par Kunena