# ============================================================================ # JOIN-WTURNDOMAIN.PS1 # Script automatique pour joindre Windows 11 au domaine W-TURN.LAN # ============================================================================ # Date: 11 janvier 2026 # Auteur: W-Turn Infrastructure Team # Version: 1.1 - Fix Execution Policy # # USAGE RECOMMANDE (methode la plus simple): # PowerShell Admin: # powershell.exe -ExecutionPolicy Bypass -File ".\Join-WTurnDomain.ps1" # # Ou si deja dans PowerShell Admin: # Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force # .\Join-WTurnDomain.ps1 # # Ce script va: # - Contourner automatiquement l'execution policy # - Verifier les prerequis (Windows 11 Pro, droits admin) # - Configurer le DNS vers le DC # - Tester la connectivite au contr?leur de domaine # - Joindre le domaine W-TURN.LAN # - Redemarrer automatiquement # ============================================================================ #Requires -RunAsAdministrator #Requires -Version 5.1 # Auto-bypass execution policy si necessaire if ((Get-ExecutionPolicy -Scope Process) -ne 'Bypass' -and (Get-ExecutionPolicy -Scope Process) -ne 'Unrestricted') { try { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force -ErrorAction Stop Write-Host "? Execution Policy configuree sur Bypass pour cette session" -ForegroundColor Green } catch { Write-Host "? Impossible de modifier l'Execution Policy automatiquement" -ForegroundColor Yellow Write-Host "Veuillez executer ce script avec:" -ForegroundColor Yellow Write-Host " powershell.exe -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -ForegroundColor Cyan Write-Host "`nOu depuis PowerShell Admin:" -ForegroundColor Yellow Write-Host " Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force" -ForegroundColor Cyan Write-Host " .\Join-WTurnDomain.ps1" -ForegroundColor Cyan pause exit 1 } } # Configuration $DomainName = "W-TURN.LAN" $DomainController = "192.168.100.250" $DomainControllerFQDN = "base.w-turn.lan" $DnsServers = @("192.168.100.250", "192.168.1.254") $DomainAdmin = "Administrator" $DomainPassword = "Samba*W-Turn*2026" # Logging configuration $LogFile = "$env:TEMP\WTurn-DomainJoin-$(Get-Date -Format 'yyyyMMdd-HHmmss').log" $LogServerUrl = "https://super.boarder.w-turn.org/utilities/log-receiver.php" # Couleurs $ColorSuccess = "Green" $ColorError = "Red" $ColorWarning = "Yellow" $ColorInfo = "Cyan" # ============================================================================ # FONCTIONS DE LOGGING # ============================================================================ function Write-Log { param( [string]$Message, [string]$Level = "INFO" ) try { $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $LogEntry = "[$Timestamp] [$Level] $Message" # Ecrire dans le fichier local (TOUJOURS) try { Add-Content -Path $LogFile -Value $LogEntry -ErrorAction Stop } catch { # Si echec ecriture fichier, on continue quand meme } # Envoyer au serveur (optionnel, en arriere-plan) Start-Job -ScriptBlock { param($Url, $Data) try { $Json = $Data | ConvertTo-Json Invoke-RestMethod -Uri $Url -Method Post -Body $Json -ContentType "application/json" -TimeoutSec 2 -ErrorAction Stop | Out-Null } catch { # Ignorer silencieusement les erreurs reseau } } -ArgumentList $LogServerUrl, @{ timestamp = $Timestamp level = $Level message = $Message computer = $env:COMPUTERNAME } | Out-Null } catch { # Ne JAMAIS crasher a cause du logging } } function Write-StepHeader { param([string]$Title) Write-Host "`n==================================================================" -ForegroundColor Cyan Write-Host "| $Title" -ForegroundColor Cyan Write-Host "==================================================================" -ForegroundColor Cyan Write-Log -Message "=== $Title ===" -Level "STEP" } function Write-Success { param([string]$Message) Write-Host "[OK] $Message" -ForegroundColor $ColorSuccess Write-Log -Message $Message -Level "SUCCESS" } function Write-ErrorMsg { param([string]$Message) Write-Host "[ERR] $Message" -ForegroundColor $ColorError Write-Log -Message $Message -Level "ERROR" } function Write-WarningMsg { param([string]$Message) Write-Host "[WARN] $Message" -ForegroundColor $ColorWarning Write-Log -Message $Message -Level "WARNING" } function Write-InfoMsg { param([string]$Message) Write-Host "[INFO] $Message" -ForegroundColor $ColorInfo Write-Log -Message $Message -Level "INFO" } function Test-Prerequisites { Write-StepHeader "VERIFICATION DES PREREQUIS" # Verifier Windows 11 Pro $OS = Get-WmiObject -Class Win32_OperatingSystem $OSVersion = $OS.Caption Write-InfoMsg "OS detecte: $OSVersion" if ($OSVersion -notlike "*Pro*" -and $OSVersion -notlike "*Enterprise*") { Write-ErrorMsg "Windows Pro ou Enterprise requis pour joindre un domaine" Write-WarningMsg "Version actuelle: $OSVersion" return $false } Write-Success "Version Windows compatible" # Verifier les droits administrateur $CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent() $Principal = New-Object Security.Principal.WindowsPrincipal($CurrentUser) if (-not $Principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-ErrorMsg "Droits administrateur requis" return $false } Write-Success "Droits administrateur OK" # Verifier si deja dans un domaine $CurrentDomain = (Get-WmiObject Win32_ComputerSystem).Domain if ($CurrentDomain -eq $DomainName) { Write-WarningMsg "PC deja membre du domaine $DomainName" $choice = Read-Host "Voulez-vous quitter puis rejoindre le domaine? (O/N)" if ($choice -ne "O") { return $false } } return $true } function Configure-DNS { Write-StepHeader "CONFIGURATION DNS" try { # Trouver l'interface reseau active $NetAdapter = Get-NetAdapter | Where-Object {$_.Status -eq "Up" -and $_.InterfaceType -eq 6} | Select-Object -First 1 if (-not $NetAdapter) { Write-ErrorMsg "Aucune interface reseau Ethernet active trouvee" return $false } $InterfaceAlias = $NetAdapter.Name Write-InfoMsg "Interface reseau: $InterfaceAlias" # Configurer les serveurs DNS Write-InfoMsg "Configuration DNS vers $($DnsServers -join ', ')..." Set-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -ServerAddresses $DnsServers # Vider le cache DNS Clear-DnsClientCache ipconfig /flushdns | Out-Null Write-Success "DNS configure avec succes" # Afficher la configuration $DnsConfig = Get-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 Write-InfoMsg "DNS configures: $($DnsConfig.ServerAddresses -join ', ')" return $true } catch { Write-ErrorMsg "Erreur lors de la configuration DNS: $_" return $false } } function Test-DomainConnectivity { Write-StepHeader "TEST DE CONNECTIVITE AU DOMAINE" $AllTestsPassed = $true # Test 1: Ping du DC Write-InfoMsg "Test ping vers $DomainController..." $PingResult = Test-Connection -ComputerName $DomainController -Count 2 -Quiet if ($PingResult) { Write-Success "Ping DC reussi" } else { Write-ErrorMsg "Ping DC echoue" $AllTestsPassed = $false } # Test 2: Resolution DNS du domaine Write-InfoMsg "Resolution DNS de $DomainName..." try { $DnsResult = Resolve-DnsName -Name $DomainName -ErrorAction Stop Write-Success "Resolution DNS reussie: $($DnsResult.IPAddress)" } catch { Write-ErrorMsg "Resolution DNS echouee" $AllTestsPassed = $false } # Test 3: Port LDAP (389) Write-InfoMsg "Test port LDAP (389)..." $LdapTest = Test-NetConnection -ComputerName $DomainController -Port 389 -WarningAction SilentlyContinue if ($LdapTest.TcpTestSucceeded) { Write-Success "Port LDAP accessible" } else { Write-ErrorMsg "Port LDAP non accessible" $AllTestsPassed = $false } # Test 4: Port Kerberos (88) Write-InfoMsg "Test port Kerberos (88)..." $KerberosTest = Test-NetConnection -ComputerName $DomainController -Port 88 -WarningAction SilentlyContinue if ($KerberosTest.TcpTestSucceeded) { Write-Success "Port Kerberos accessible" } else { Write-ErrorMsg "Port Kerberos non accessible" $AllTestsPassed = $false } # Test 5: Port SMB (445) Write-InfoMsg "Test port SMB (445)..." $SmbTest = Test-NetConnection -ComputerName $DomainController -Port 445 -WarningAction SilentlyContinue if ($SmbTest.TcpTestSucceeded) { Write-Success "Port SMB accessible" } else { Write-ErrorMsg "Port SMB non accessible" $AllTestsPassed = $false } # Test 6: Acces au partage SYSVOL Write-InfoMsg "Test acces partage SYSVOL..." try { $SysvolPath = "\\$DomainControllerName\sysvol" $SysvolTest = Test-Path $SysvolPath -ErrorAction Stop if ($SysvolTest) { Write-Success "Partage SYSVOL accessible" } } catch { Write-WarningMsg "Partage SYSVOL non accessible (normal avant domain join)" } return $AllTestsPassed } function Join-Domain { Write-StepHeader "JONCTION AU DOMAINE $DomainName" try { # Creer les credentials $SecurePassword = ConvertTo-SecureString $DomainPassword -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($DomainAdmin, $SecurePassword) Write-InfoMsg "Jonction au domaine en cours..." Write-InfoMsg "Domaine: $DomainName" Write-InfoMsg "Utilisateur: $DomainAdmin" # Joindre le domaine Add-Computer -DomainName $DomainName -Credential $Credential -Force -ErrorAction Stop Write-Success "SUCC?S ! PC joint au domaine $DomainName" Write-InfoMsg "Un redemarrage est necessaire pour finaliser" return $true } catch { Write-ErrorMsg "Erreur lors de la jonction: $_" Write-InfoMsg "Verifiez que:" Write-InfoMsg " - Le mot de passe Administrator est correct" Write-InfoMsg " - Le contr?leur de domaine est accessible" Write-InfoMsg " - Les ports reseau sont ouverts" return $false } } function Show-PostJoinInstructions { Write-StepHeader "INSTRUCTIONS POST-REDEMARRAGE" Write-Host "" Write-InfoMsg "Apres le redemarrage:" Write-Host "" Write-Host "1?? Sur l'ecran de connexion, cliquer sur 'Autre utilisateur'" -ForegroundColor Yellow Write-Host "" Write-Host "2?? Se connecter avec:" -ForegroundColor Yellow Write-Host " Nom d'utilisateur: Administrator@$DomainName" -ForegroundColor White Write-Host " ou: $DomainName\Administrator" -ForegroundColor White Write-Host " Mot de passe: $DomainPassword" -ForegroundColor White Write-Host "" Write-Host "3?? Connecter l'imprimante reseau (PowerShell Admin):" -ForegroundColor Yellow Write-Host " Add-Printer -ConnectionName '\\BASE.W-TURN.LAN\EpsonWF2930'" -ForegroundColor White Write-Host "" Write-Host "4?? Forcer les strategies de groupe:" -ForegroundColor Yellow Write-Host " gpupdate /force" -ForegroundColor White Write-Host "" Write-Host "5?? Synchroniser l'heure avec le DC:" -ForegroundColor Yellow Write-Host " w32tm /resync /force" -ForegroundColor White Write-Host "" } # ============================================================================ # SCRIPT PRINCIPAL # ============================================================================ # Initialiser le logging Write-Log -Message "===== DEBUT JONCTION DOMAINE W-TURN.LAN =====" -Level "START" Write-Log -Message "Computer: $env:COMPUTERNAME" -Level "INFO" Write-Log -Message "User: $env:USERNAME" -Level "INFO" Write-Log -Message "PowerShell Version: $($PSVersionTable.PSVersion)" -Level "INFO" try { Clear-Host Write-Host "==================================================================" -ForegroundColor Cyan Write-Host "| |" -ForegroundColor Cyan Write-Host "| JONCTION AUTOMATIQUE DOMAINE W-TURN.LAN |" -ForegroundColor Cyan Write-Host "| |" -ForegroundColor Cyan Write-Host "==================================================================" -ForegroundColor Cyan Write-Host "" Write-InfoMsg "Version: 1.1 - Date: 11 janvier 2026" Write-InfoMsg "Infrastructure: W-Turn / base.w-turn.lan" Write-Host "" Write-Host "? Log file: $LogFile" -ForegroundColor Yellow Write-Host "" # Etape 1: Verification des prerequis if (-not (Test-Prerequisites)) { Write-Host "" Write-ErrorMsg "Les prerequis ne sont pas satisfaits" Write-Host "" throw "Prerequisites check failed" } # Etape 2: Configuration DNS if (-not (Configure-DNS)) { Write-Host "" Write-ErrorMsg "Echec de la configuration DNS" Write-Host "" throw "DNS configuration failed" } # Pause pour laisser le DNS se propager Write-InfoMsg "Pause de 3 secondes pour propagation DNS..." Start-Sleep -Seconds 3 # Etape 3: Test de connectivite if (-not (Test-DomainConnectivity)) { Write-Host "" Write-WarningMsg "Certains tests de connectivite ont echoue" $choice = Read-Host "Continuer malgre tout? (O/N)" if ($choice -ne "O") { Write-InfoMsg "Operation annulee" throw "User cancelled due to connectivity issues" } } # Etape 4: Jonction au domaine if (-not (Join-Domain)) { Write-Host "" Write-ErrorMsg "Echec de la jonction au domaine" Write-Host "" Write-InfoMsg "Pour plus d'aide, consultez: WINDOWS11_DOMAIN_JOIN_GUIDE.md" Write-Host "" throw "Domain join failed" } # Etape 5: Instructions post-jonction Show-PostJoinInstructions # Etape 6: Proposition de redemarrage Write-Host "" Write-Host "==================================================================" -ForegroundColor Green Write-Host "| [OK] JONCTION REUSSIE ! |" -ForegroundColor Green Write-Host "==================================================================" -ForegroundColor Green Write-Host "" Write-Log -Message "===== JONCTION REUSSIE =====" -Level "SUCCESS" $Reboot = Read-Host "Redemarrer maintenant? (O/N)" if ($Reboot -eq "O") { Write-InfoMsg "Redemarrage dans 10 secondes..." Write-WarningMsg "Sauvegardez vos fichiers ouverts !" Write-Log -Message "Reboot initiated by user" -Level "INFO" Start-Sleep -Seconds 10 Restart-Computer -Force } else { Write-InfoMsg "Redemarrez manuellement pour finaliser la jonction" Write-Host "" } } catch { Write-Host "" Write-Host "==================================================================" -ForegroundColor Red Write-Host "| [ERR] ERREUR CRITIQUE |" -ForegroundColor Red Write-Host "==================================================================" -ForegroundColor Red Write-Host "" Write-ErrorMsg "Exception: $($_.Exception.Message)" Write-ErrorMsg "Ligne: $($_.InvocationInfo.ScriptLineNumber)" Write-Log -Message "ERREUR CRITIQUE: $($_.Exception.Message)" -Level "CRITICAL" Write-Log -Message "Stack: $($_.ScriptStackTrace)" -Level "CRITICAL" Write-Host "" Write-Host "? Log complet disponible ici:" -ForegroundColor Yellow Write-Host " $LogFile" -ForegroundColor Cyan Write-Host "" Write-InfoMsg "Envoyez ce fichier log pour diagnostic" } finally { Write-Log -Message "===== FIN SCRIPT =====" -Level "END" Write-Host "" Read-Host "Appuyez sur Entree pour quitter" }