# Script 1: Configuration initiale du serveur Windows 2012 R2
# Enregistrer sous ConfigureServer.ps1
# Exécuter en tant qu'administrateur
param(
[Parameter(Mandatory=$true)]
[string]$ServerName,
[Parameter(Mandatory=$true)]
[string]$IPAddress,
[Parameter(Mandatory=$false)]
[string]$SubnetMask = "255.255.255.0",
[Parameter(Mandatory=$false)]
[string]$Gateway = "10.4.105.254",
[Parameter(Mandatory=$false)]
[string]$DNSServer = "134.59.136.1"
)
Write-Host "Configuration du serveur Windows 2012 R2..." -ForegroundColor Green
# 1. Configurer le nom du serveur
Write-Host "Configuration du nom du serveur: $ServerName" -ForegroundColor Cyan
Rename-Computer -NewName $ServerName -Force
# 2. Configurer l'interface réseau
$interfaceIndex = (Get-NetAdapter | Where-Object {$_.Status -eq "Up"}).ifIndex
if (-not $interfaceIndex) {
Write-Host "Aucune interface réseau active trouvée!" -ForegroundColor Red
exit 1
}
Write-Host "Configuration de l'adresse IP: $IPAddress" -ForegroundColor Cyan
# Supprimer toutes les configurations IP existantes
Remove-NetIPAddress -InterfaceIndex $interfaceIndex -Confirm:$false -ErrorAction
SilentlyContinue
Remove-NetRoute -InterfaceIndex $interfaceIndex -Confirm:$false -ErrorAction
SilentlyContinue
# Ajouter la nouvelle configuration IP
New-NetIPAddress -InterfaceIndex $interfaceIndex -IPAddress $IPAddress -
PrefixLength 24 -DefaultGateway $Gateway
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ServerAddresses
$DNSServer
Write-Host "Configuration réseau terminée" -ForegroundColor Green
Write-Host "Redémarrage nécessaire pour appliquer les changements de nom" -
ForegroundColor Yellow
Write-Host "Exécutez 'Restart-Computer' pour redémarrer le serveur" -
ForegroundColor Yellow
# Script 2: Installation et configuration d'Active Directory
# Enregistrer sous InstallAD.ps1
# Exécuter en tant qu'administrateur après le redémarrage du serveur
param(
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$false)]
[string]$DomainNetbiosName = "",
[Parameter(Mandatory=$false)]
[string]$SafeModePassword = "P@ssw0rd",
[Parameter(Mandatory=$false)]
[string]$DomainMode = "Win2012",
[Parameter(Mandatory=$false)]
[string]$ForestMode = "Win2012"
)
Write-Host "Installation et configuration d'Active Directory..." -ForegroundColor
Green
# Générer le NetBIOS name s'il n'est pas fourni
if ($DomainNetbiosName -eq "") {
$DomainNetbiosName = $DomainName.Split('.')[0].ToUpper()
}
# 1. Installer le rôle AD DS
Write-Host "Installation du rôle AD DS..." -ForegroundColor Cyan
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
# 2. Importer le module AD DS Deployment
Import-Module ADDSDeployment
# 3. Convertir le mot de passe en SecureString
$securePassword = ConvertTo-SecureString $SafeModePassword -AsPlainText -Force
# 4. Configurer le domaine
Write-Host "Configuration du domaine: $DomainName (NetBIOS: $DomainNetbiosName)..."
-ForegroundColor Cyan
Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-DomainMode $DomainMode `
-DomainName $DomainName `
-DomainNetbiosName $DomainNetbiosName `
-ForestMode $ForestMode `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:\Windows\SYSVOL" `
-SafeModeAdministratorPassword $securePassword `
-Force:$true
# Le serveur redémarrera automatiquement une fois l'installation terminée
# Script 3: Création des partages et des dossiers utilisateurs
# Enregistrer sous CreateShares.ps1
# Exécuter en tant qu'administrateur après l'installation d'AD
param(
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$false)]
[string]$HomesPath = "C:\Homes",
[Parameter(Mandatory=$false)]
[string]$ProfilesPath = "C:\Profiles"
)
Write-Host "Création des partages réseau et configuration des permissions..." -
ForegroundColor Green
$domainNetbios = $DomainName.Split('.')[0].ToUpper()
# 1. Créer et partager le dossier Homes
Write-Host "Création du partage Homes..." -ForegroundColor Cyan
if (-not (Test-Path $HomesPath)) {
New-Item -Path $HomesPath -ItemType Directory -Force
}
# Vérifier si le partage existe déjà, sinon le créer
$homeShare = Get-SmbShare -Name "Homes" -ErrorAction SilentlyContinue
if (-not $homeShare) {
New-SmbShare -Name "Homes" -Path $HomesPath -FullAccess "Administrateur",
"SYSTEM", "$domainNetbios\Domain Users"
} else {
# Mettre à jour les permissions si le partage existe
Grant-SmbShareAccess -Name "Homes" -AccountName "Administrateur", "SYSTEM",
"$domainNetbios\Domain Users" -AccessRight Full -Force
}
# Supprimer l'accès "Everyone" si présent
Revoke-SmbShareAccess -Name "Homes" -AccountName "Everyone" -Force -ErrorAction
SilentlyContinue
# 2. Configurer les permissions NTFS pour Homes
$acl = Get-Acl -Path $HomesPath
$acl.SetAccessRuleProtection($true, $false) # Désactiver l'héritage
# Créer les règles d'accès
$adminRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators",
"FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$systemRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl",
"ContainerInherit,ObjectInherit", "None", "Allow")
$creatorRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", "FullControl",
"ContainerInherit,ObjectInherit", "None", "Allow")
# Supprimer toutes les règles existantes
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
# Ajouter les nouvelles règles
$acl.AddAccessRule($adminRule)
$acl.AddAccessRule($systemRule)
$acl.AddAccessRule($creatorRule)
# Appliquer les permissions
Set-Acl -Path $HomesPath -AclObject $acl
# 3. Créer et partager le dossier Profiles
Write-Host "Création du partage Profiles..." -ForegroundColor Cyan
if (-not (Test-Path $ProfilesPath)) {
New-Item -Path $ProfilesPath -ItemType Directory -Force
}
# Vérifier si le partage existe déjà, sinon le créer
$profileShare = Get-SmbShare -Name "Profiles" -ErrorAction SilentlyContinue
if (-not $profileShare) {
New-SmbShare -Name "Profiles" -Path $ProfilesPath -ChangeAccess
"$domainNetbios\Domain Users"
} else {
# Mettre à jour les permissions si le partage existe
Grant-SmbShareAccess -Name "Profiles" -AccountName "$domainNetbios\Domain
Users" -AccessRight Change -Force
}
# Supprimer l'accès "Everyone" si présent
Revoke-SmbShareAccess -Name "Profiles" -AccountName "Everyone" -Force -ErrorAction
SilentlyContinue
# 4. Configurer les permissions NTFS pour Profiles
$acl = Get-Acl -Path $ProfilesPath
$acl.SetAccessRuleProtection($true, $false) # Désactiver l'héritage
# Créer les règles d'accès
$adminRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators",
"FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$systemRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl",
"ContainerInherit,ObjectInherit", "None", "Allow")
$domainUsersRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("$domainNetbios\Domain Users",
"ReadAndExecute, CreateDirectories", "ContainerInherit,ObjectInherit", "None",
"Allow")
# Supprimer toutes les règles existantes
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
# Ajouter les nouvelles règles
$acl.AddAccessRule($adminRule)
$acl.AddAccessRule($systemRule)
$acl.AddAccessRule($domainUsersRule)
# Appliquer les permissions
Set-Acl -Path $ProfilesPath -AclObject $acl
Write-Host "Configuration des partages terminée" -ForegroundColor Green
# Script 4: Création des utilisateurs
# Enregistrer sous CreateUsers.ps1
# Exécuter en tant qu'administrateur après la création des partages
param(
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$true)]
[string]$ServerName,
[Parameter(Mandatory=$false)]
[string]$Password = "P@ssw0rd123",
[Parameter(Mandatory=$false)]
[string]$HomesPath = "C:\Homes"
)
Write-Host "Création des utilisateurs dans le domaine..." -ForegroundColor Green
$domainNetbios = $DomainName.Split('.')[0].ToUpper()
# Convertir le mot de passe en format sécurisé
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
# Fonction pour créer un utilisateur avec un lecteur réseau et un dossier personnel
function Create-DomainUser {
param (
[string]$Username,
[string]$FirstName,
[string]$LastName,
[string]$ServerName,
[string]$DomainName,
[string]$HomesPath,
[SecureString]$Password
)
# Vérifier si l'utilisateur existe déjà
$userExists = Get-ADUser -Filter {SamAccountName -eq $Username} -ErrorAction
SilentlyContinue
if (-not $userExists) {
Write-Host "Création de l'utilisateur: $Username" -ForegroundColor Cyan
# Créer l'utilisateur
New-ADUser -Name "$FirstName $LastName" `
-GivenName $FirstName `
-Surname $LastName `
-SamAccountName $Username `
-UserPrincipalName "$Username@$DomainName" `
-AccountPassword $Password `
-Enabled $true `
-PasswordNeverExpires $true
# Configurer le lecteur réseau
Set-ADUser -Identity $Username -HomeDrive "Z" -HomeDirectory "\\
$ServerName\Homes\$Username"
# Configurer le profil itinérant
Set-ADUser -Identity $Username -ProfilePath "\\$ServerName\Profiles\
$Username"
# Créer le dossier personnel de l'utilisateur
$userHomePath = Join-Path -Path $HomesPath -ChildPath $Username
if (-not (Test-Path $userHomePath)) {
New-Item -Path $userHomePath -ItemType Directory -Force
}
# Configurer les permissions du dossier personnel
$acl = Get-Acl -Path $userHomePath
$userRule = New-Object
System.Security.AccessControl.FileSystemAccessRule("$domainNetbios\$Username",
"FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.AddAccessRule($userRule)
Set-Acl -Path $userHomePath -AclObject $acl
Write-Host "Utilisateur $Username créé avec succès" -ForegroundColor Green
} else {
Write-Host "L'utilisateur $Username existe déjà" -ForegroundColor Yellow
}
}
# Créer user1
Create-DomainUser -Username "user1" -FirstName "User" -LastName "One" -ServerName
$ServerName -DomainName $DomainName -HomesPath $HomesPath -Password $securePassword
# Créer user2
Create-DomainUser -Username "user2" -FirstName "User" -LastName "Two" -ServerName
$ServerName -DomainName $DomainName -HomesPath $HomesPath -Password $securePassword
Write-Host "Création des utilisateurs terminée" -ForegroundColor Green
# Script 5: Configuration des stratégies de mot de passe
# Enregistrer sous ConfigurePasswordPolicy.ps1
# Exécuter en tant qu'administrateur
param(
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$false)]
[int]$MinPasswordLength = 4,
[Parameter(Mandatory=$false)]
[int]$PasswordHistoryCount = 3,
[Parameter(Mandatory=$false)]
[int]$MaxPasswordAge = 90,
[Parameter(Mandatory=$false)]
[bool]$ComplexityEnabled = $false
)
Write-Host "Configuration des stratégies de mot de passe..." -ForegroundColor Green
# Modifier les stratégies de mot de passe du domaine
Set-ADDefaultDomainPasswordPolicy -Identity $DomainName `
-ComplexityEnabled $ComplexityEnabled `
-MinPasswordLength $MinPasswordLength `
-MinPasswordAge (New-TimeSpan -Days 0) `
-MaxPasswordAge (New-TimeSpan -Days $MaxPasswordAge) `
-PasswordHistoryCount $PasswordHistoryCount `
-LockoutThreshold 0
Write-Host "Stratégies de mot de passe configurées avec succès" -ForegroundColor
Green
Write-Host "- Longueur minimale: $MinPasswordLength caractères" -ForegroundColor
Cyan
Write-Host "- Complexité requise: $ComplexityEnabled" -ForegroundColor Cyan
Write-Host "- Historique des mots de passe: $PasswordHistoryCount" -ForegroundColor
Cyan
Write-Host "- Durée maximale: $MaxPasswordAge jours" -ForegroundColor Cyan
# Script 6: Déploiement d'applications
# Enregistrer sous DeployApplication.ps1
# Exécuter en tant qu'administrateur
param(
[Parameter(Mandatory=$true)]
[string]$ApplicationUrl,
[Parameter(Mandatory=$true)]
[string]$ApplicationName,
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$false)]
[string]$DownloadPath = "C:\Windows\SYSVOL\sysvol\$DomainName\scripts"
)
Write-Host "Configuration du déploiement d'application via GPO..." -ForegroundColor
Green
# 1. Créer le dossier de destination si nécessaire
if (-not (Test-Path $DownloadPath)) {
New-Item -Path $DownloadPath -ItemType Directory -Force
}
# 2. Télécharger le fichier MSI
$fileName = Split-Path -Path $ApplicationUrl -Leaf
$filePath = Join-Path -Path $DownloadPath -ChildPath $fileName
Write-Host "Téléchargement de $ApplicationUrl vers $filePath" -ForegroundColor Cyan
try {
Invoke-WebRequest -Uri $ApplicationUrl -OutFile $filePath -ErrorAction Stop
Write-Host "Téléchargement terminé" -ForegroundColor Green
} catch {
Write-Host "Erreur lors du téléchargement: $_" -ForegroundColor Red
exit 1
}
# 3. Créer un nouvel objet GPO
$gpoName = "Install $ApplicationName"
Write-Host "Création de l'objet GPO: $gpoName" -ForegroundColor Cyan
# Vérifier si le GPO existe déjà
$existingGPO = Get-GPO -Name $gpoName -ErrorAction SilentlyContinue
if ($existingGPO) {
Write-Host "Le GPO $gpoName existe déjà, suppression en cours..." -
ForegroundColor Yellow
Remove-GPO -Name $gpoName -Confirm:$false
}
# Créer le nouveau GPO
$gpo = New-GPO -Name $gpoName
# 4. Créer un script de démarrage pour installer le MSI
$scriptContent = @"
msiexec /i "$filePath" /qn
"@
$scriptPath = Join-Path -Path $DownloadPath -ChildPath
"Install_$ApplicationName.cmd"
$scriptContent | Out-File -FilePath $scriptPath -Encoding ascii
# 5. Configurer le GPO avec le script de démarrage
$gpo | Set-GPRegistryValue -Key "HKLM\Software\Microsoft\Windows\CurrentVersion\
RunOnce" -ValueName "Install$ApplicationName" -Type String -Value "cmd.exe /c
$scriptPath"
# 6. Lier le GPO au domaine
New-GPLink -Name $gpoName -Target "DC=$($DomainName.Replace('.',',DC='))"
# 7. Forcer la mise à jour des stratégies de groupe
Write-Host "Mise à jour des stratégies de groupe..." -ForegroundColor Cyan
Invoke-GPUpdate -Force
Write-Host "Configuration du déploiement d'application terminée" -ForegroundColor
Green
Write-Host "L'application $ApplicationName sera installée à la prochaine connexion"
-ForegroundColor Cyan
# Script 7: Configuration du client Windows pour rejoindre le domaine
# Enregistrer sous JoinDomain.ps1
# Exécuter en tant qu'administrateur sur le client Windows
param(
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$true)]
[string]$DomainControllerIP,
[Parameter(Mandatory=$true)]
[string]$ClientName,
[Parameter(Mandatory=$false)]
[string]$Username = "Administrator",
[Parameter(Mandatory=$false)]
[string]$Password = "Win2012a"
)
Write-Host "Configuration du client Windows et jonction au domaine..." -
ForegroundColor Green
# 1. Configurer le DNS pour pointer vers le contrôleur de domaine
$interfaceIndex = (Get-NetAdapter | Where-Object {$_.Status -eq "Up"}).ifIndex
if (-not $interfaceIndex) {
Write-Host "Aucune interface réseau active trouvée!" -ForegroundColor Red
exit 1
}
Write-Host "Configuration du DNS pour utiliser le contrôleur de domaine:
$DomainControllerIP" -ForegroundColor Cyan
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ServerAddresses
$DomainControllerIP
# 2. Vérifier la connexion au contrôleur de domaine
Write-Host "Test de la connexion au contrôleur de domaine..." -ForegroundColor Cyan
if (-not (Test-Connection -ComputerName $DomainControllerIP -Count 1 -Quiet)) {
Write-Host "Impossible de joindre le contrôleur de domaine!" -ForegroundColor
Red
exit 1
}
# 3. Configurer le nom du client
Write-Host "Configuration du nom du client: $ClientName" -ForegroundColor Cyan
$currentName = $env:COMPUTERNAME
if ($currentName -ne $ClientName) {
Rename-Computer -NewName $ClientName -Force
Write-Host "Le nom de l'ordinateur a été changé, un redémarrage est nécessaire"
-ForegroundColor Yellow
$restart = $true
} else {
Write-Host "Le nom de l'ordinateur est déjà configuré correctement" -
ForegroundColor Green
}
# 4. Créer un objet d'identification pour joindre le domaine
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ("$DomainName\
$Username", $securePassword)
# 5. Joindre l'ordinateur au domaine
try {
Write-Host "Jonction au domaine $DomainName en cours..." -ForegroundColor Cyan
Add-Computer -DomainName $DomainName -Credential $credential -Force -
ErrorAction Stop
Write-Host "Jonction au domaine réussie!" -ForegroundColor Green
$restart = $true
} catch {
Write-Host "Erreur lors de la jonction au domaine: $_" -ForegroundColor Red
exit 1
}
# 6. Redémarrer si nécessaire
if ($restart) {
Write-Host "Un redémarrage est nécessaire pour appliquer les changements" -
ForegroundColor Yellow
$restartNow = Read-Host "Voulez-vous redémarrer maintenant? (O/N)"
if ($restartNow -eq "O" -or $restartNow -eq "o") {
Restart-Computer -Force
}
} else {
Write-Host "Aucun redémarrage n'est nécessaire" -ForegroundColor Green
}
# Script 8: Script global pour lancer toutes les opérations
# Enregistrer sous AutomateTasks.ps1
# Exécuter en tant qu'administrateur
param(
[Parameter(Mandatory=$true)]
[string]$ServerName,
[Parameter(Mandatory=$true)]
[string]$ServerIP,
[Parameter(Mandatory=$true)]
[string]$DomainName,
[Parameter(Mandatory=$false)]
[string]$SafeModePassword = "P@ssw0rd",
[Parameter(Mandatory=$false)]
[string]$UserPassword = "P@ssw0rd123",
[Parameter(Mandatory=$false)]
[string]$PuttyUrl = "https://www.i3s.unice.fr/~urvoy/docs/M2102/putty_suite-
0.58.msi"
)
Write-Host "=== SCRIPT D'AUTOMATISATION DES TÂCHES WINDOWS SERVER 2012 R2 ===" -
ForegroundColor Magenta
Write-Host "Ce script va automatiser les étapes suivantes:" -ForegroundColor Cyan
Write-Host "1. Configuration du serveur (nom et réseau)" -ForegroundColor White
Write-Host "2. Installation d'Active Directory" -ForegroundColor White
Write-Host "3. Création des partages réseau" -ForegroundColor White
Write-Host "4. Création des utilisateurs du domaine" -ForegroundColor White
Write-Host "5. Configuration des stratégies de mot de passe" -ForegroundColor White
Write-Host "6. Déploiement d'application via GPO" -ForegroundColor White
Write-Host
$confirmation = Read-Host "Êtes-vous sûr de vouloir continuer? (O/N)"
if ($confirmation -ne "O" -and $confirmation -ne "o") {
Write-Host "Opération annulée" -ForegroundColor Yellow
exit
}
# 1. Configuration du serveur
Write-Host "ÉTAPE 1: Configuration du serveur" -ForegroundColor Green
.\ConfigureServer.ps1 -ServerName $ServerName -IPAddress $ServerIP
# Attendre le redémarrage
$reboot = Read-Host "Un redémarrage est nécessaire. Veuillez redémarrer le serveur
et appuyer sur une touche une fois le serveur redémarré..."
# 2. Installation d'Active Directory
Write-Host "ÉTAPE 2: Installation d'Active Directory" -ForegroundColor Green
.\InstallAD.ps1 -DomainName $DomainName -SafeModePassword $SafeModePassword
# Attendre le redémarrage
$reboot = Read-Host "Le serveur va redémarrer automatiquement. Veuillez appuyer sur
une touche une fois le serveur redémarré..."
# 3. Création des partages réseau
Write-Host "ÉTAPE 3: Création des partages réseau" -ForegroundColor Green
.\CreateShares.ps1 -DomainName $DomainName
# 4. Création des utilisateurs du domaine
Write-Host "ÉTAPE 4: Création des utilisateurs du domaine" -ForegroundColor Green
.\CreateUsers.ps1 -DomainName $DomainName -ServerName $ServerName -Password
$UserPassword
# 5. Configuration des stratégies de mot de passe
Write-Host "ÉTAPE 5: Configuration des stratégies de mot de passe" -ForegroundColor
Green
.\ConfigurePasswordPolicy.ps1 -DomainName $DomainName -MinPasswordLength 4 -
ComplexityEnabled $false
# 6. Déploiement d'application via GPO
Write-Host "ÉTAPE 6: Déploiement d'application via GPO" -ForegroundColor Green
.\DeployApplication.ps1 -ApplicationUrl $PuttyUrl -ApplicationName "PuTTY" -
DomainName $DomainName
Write-Host "=== AUTOMATISATION TERMINÉE ===" -ForegroundColor Magenta
Write-Host "Toutes les tâches ont été exécutées avec succès" -ForegroundColor Green
Write-Host
Write-Host "Pour configurer un client Windows et le joindre au domaine:" -
ForegroundColor Cyan
Write-Host ".\JoinDomain.ps1 -DomainName $DomainName -DomainControllerIP $ServerIP
-ClientName [NOM_CLIENT]" -ForegroundColor White