Fix: correct OU path, skip missing packages, add webhook notification

This commit is contained in:
2026-03-30 20:34:26 +00:00
parent 7de663f34a
commit 79b2fb19f8

View File

@@ -13,6 +13,7 @@
param( param(
[Parameter(Mandatory=$true)] [Parameter(Mandatory=$true)]
[ValidateSet("IT","Accounting","Design","Management","Teaching","Admin")]
[string]$Department, [string]$Department,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
@@ -27,26 +28,42 @@ param(
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$LogFile = "C:\MABDC\Logs\domain-join.log" $LogFile = "C:\MABDC\Logs\domain-join.log"
$WebhookUrl = "https://webhooks.tasklet.ai/v1/public/webhook?token=64e387124cc212b5231a29d04c6e09aa"
function Write-Log { function Write-Log {
param([string]$Message) param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$entry = "[$timestamp] $Message" $entry = "[$timestamp] $Message"
Write-Host $entry -ForegroundColor Green Write-Host $entry -ForegroundColor Green
$null = New-Item -ItemType Directory -Path (Split-Path $LogFile) -Force -ErrorAction SilentlyContinue
Add-Content -Path $LogFile -Value $entry -ErrorAction SilentlyContinue Add-Content -Path $LogFile -Value $entry -ErrorAction SilentlyContinue
} }
function Send-WebhookNotification {
param([hashtable]$Data)
try {
$body = $Data | ConvertTo-Json -Compress
Invoke-RestMethod -Uri $WebhookUrl -Method POST -Body $body -ContentType "application/json" -UseBasicParsing -ErrorAction SilentlyContinue | Out-Null
Write-Log "Webhook notification sent"
} catch {
Write-Log "Warning: Could not send webhook notification: $_"
}
}
# Pre-flight checks # Pre-flight checks
Write-Log "=== MABDC Domain Join Script v1.0 ===" Write-Log "=== MABDC Domain Join Script v1.1 ==="
Write-Log "Starting pre-flight checks..." Write-Log "Starting pre-flight checks..."
# Ensure log directory exists
$null = New-Item -ItemType Directory -Path "C:\MABDC\Logs" -Force -ErrorAction SilentlyContinue
# Check Windows edition # Check Windows edition
$edition = (Get-WindowsEdition -Online).Edition $edition = (Get-WindowsEdition -Online).Edition
if ($edition -match "Home|Core") { if ($edition -match "Home|Core") {
Write-Host "ERROR: Windows 11 Home cannot join a domain. You need Pro or Enterprise." -ForegroundColor Red Write-Host "ERROR: Windows 11 Home cannot join a domain. You need Pro or Enterprise." -ForegroundColor Red
exit 1 exit 1
} }
Write-Log "Windows Edition: $edition " Write-Log "Windows Edition: $edition OK"
# Check if already domain-joined # Check if already domain-joined
$currentDomain = (Get-WmiObject Win32_ComputerSystem).Domain $currentDomain = (Get-WmiObject Win32_ComputerSystem).Domain
@@ -70,7 +87,7 @@ if ($PCName) {
$currentName = $env:COMPUTERNAME $currentName = $env:COMPUTERNAME
if ($currentName -ne $PCName) { if ($currentName -ne $PCName) {
Rename-Computer -NewName $PCName -Force Rename-Computer -NewName $PCName -Force
Write-Log "PC renamed to $PCName (reboot required)" Write-Log "PC renamed to $PCName (will apply after reboot)"
} }
} }
@@ -82,16 +99,20 @@ foreach ($adapter in $adapters) {
Write-Log "DNS set on adapter: $($adapter.Name)" Write-Log "DNS set on adapter: $($adapter.Name)"
} }
# Flush DNS cache
Clear-DnsClientCache
Write-Log "DNS cache flushed"
# Test AD connectivity # Test AD connectivity
Write-Log "Testing connection to AD server..." Write-Log "Testing connection to AD server..."
$adTest = Test-NetConnection -ComputerName "dc1.mabdc.org" -Port 389 -WarningAction SilentlyContinue $adTest = Test-NetConnection -ComputerName "dc1.mabdc.org" -Port 389 -WarningAction SilentlyContinue
if ($adTest.TcpTestSucceeded) { if ($adTest.TcpTestSucceeded) {
Write-Log "AD server reachable on LDAP (389) " Write-Log "AD server reachable on LDAP (389) OK"
} else { } else {
Write-Log "WARNING: Cannot reach AD server on port 389. Trying port 636 (LDAPS)..." Write-Log "WARNING: Cannot reach AD server on port 389. Trying port 636 (LDAPS)..."
$adTest2 = Test-NetConnection -ComputerName "dc1.mabdc.org" -Port 636 -WarningAction SilentlyContinue $adTest2 = Test-NetConnection -ComputerName "dc1.mabdc.org" -Port 636 -WarningAction SilentlyContinue
if ($adTest2.TcpTestSucceeded) { if ($adTest2.TcpTestSucceeded) {
Write-Log "AD server reachable on LDAPS (636) " Write-Log "AD server reachable on LDAPS (636) OK"
} else { } else {
Write-Host "ERROR: Cannot reach AD server. Check network/firewall." -ForegroundColor Red Write-Host "ERROR: Cannot reach AD server. Check network/firewall." -ForegroundColor Red
exit 1 exit 1
@@ -101,17 +122,20 @@ if ($adTest.TcpTestSucceeded) {
# Join domain (if not already joined) # Join domain (if not already joined)
if ($currentDomain -ne $DomainName) { if ($currentDomain -ne $DomainName) {
Write-Log "Joining domain $DomainName..." Write-Log "Joining domain $DomainName..."
$cred = Get-Credential -Message "Enter domain admin credentials for $DomainName" $cred = Get-Credential -Message "Enter domain admin credentials for $DomainName (e.g. MABDC\Administrator)"
$ouPath = "OU=$Department,DC=mabdc,DC=org" # OU path: department sub-OU under Staff
$ouPath = "OU=$Department,OU=Staff,DC=mabdc,DC=org"
try { try {
Add-Computer -DomainName $DomainName -OUPath $ouPath -Credential $cred -Force Add-Computer -DomainName $DomainName -OUPath $ouPath -Credential $cred -Force -ErrorAction Stop
Write-Log "Successfully joined $DomainName in OU=$Department " Write-Log "Successfully joined $DomainName in $ouPath OK"
} catch { } catch {
Write-Log "Trying without OU specification..." Write-Log "Could not join with OU path ($ouPath), trying default OU..."
Add-Computer -DomainName $DomainName -Credential $cred -Force Add-Computer -DomainName $DomainName -Credential $cred -Force
Write-Log "Successfully joined $DomainName (default OU) " Write-Log "Successfully joined $DomainName (default OU) OK"
} }
} else {
Write-Log "Already in domain - skipping domain join"
} }
# Install Chocolatey # Install Chocolatey
@@ -120,9 +144,9 @@ if (!(Get-Command choco -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
Write-Log "Chocolatey installed " Write-Log "Chocolatey installed OK"
} else { } else {
Write-Log "Chocolatey already installed " Write-Log "Chocolatey already installed OK"
} }
# Refresh PATH # Refresh PATH
@@ -130,35 +154,41 @@ $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";"
# Add MABDC Chocolatey source # Add MABDC Chocolatey source
Write-Log "Adding MABDC package repository..." Write-Log "Adding MABDC package repository..."
choco source add --name=mabdc --source="https://repo.mabdc.com/api/packages/mabdc/nuget/v2" --priority=1 -y choco source add --name=mabdc --source="https://repo.mabdc.com/api/packages/mabdc/nuget/v2" --priority=1 -y 2>&1 | Out-Null
Write-Log "MABDC repo added " Write-Log "MABDC repo added OK"
# Install base packages # Install base packages from public Chocolatey
Write-Log "Installing base packages (this may take several minutes)..." Write-Log "Installing base packages..."
$basePackages = @( $basePackages = @(
"mabdc-base-config", @{name="googlechrome"; source="chocolatey"},
"mabdc-debloat", @{name="7zip"; source="chocolatey"},
"mabdc-nextdns-config", @{name="notepadplusplus"; source="chocolatey"},
"mabdc-wallpaper", @{name="vlc"; source="chocolatey"}
"mabdc-chrome-enterprise",
"mabdc-rustdesk"
) )
foreach ($pkg in $basePackages) { foreach ($pkg in $basePackages) {
Write-Log "Installing $pkg..." Write-Log "Installing $($pkg.name)..."
choco install $pkg --source=mabdc -y --no-progress 2>&1 | Out-Null choco install $pkg.name --source=$($pkg.source) -y --no-progress 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) {
Write-Log "$pkg installed " Write-Log "$($pkg.name) installed OK"
} else { } else {
Write-Log "WARNING: $pkg may have had issues (exit code: $LASTEXITCODE)" Write-Log "WARNING: $($pkg.name) may have had issues (exit code: $LASTEXITCODE)"
} }
} }
# Install department-specific packages # Try MABDC-specific packages (optional - skip if not available)
Write-Log "Installing department packages for: $Department" Write-Log "Checking for MABDC department packages..."
$deptPackage = "dept-$($Department.ToLower())" $mabdcPackages = @("mabdc-base-config", "mabdc-wallpaper", "mabdc-rustdesk")
choco install $deptPackage --source=mabdc -y --no-progress 2>&1 | Out-Null foreach ($pkg in $mabdcPackages) {
$available = choco search $pkg --source=mabdc --exact 2>&1 | Select-String -Pattern $pkg -Quiet
if ($available) {
choco install $pkg --source=mabdc -y --no-progress 2>&1 | Out-Null
Write-Log "$pkg installed OK"
} else {
Write-Log "Skipping $pkg (not yet published in MABDC repo)"
}
}
# Set up auto-update scheduled task # Set up auto-update scheduled task
Write-Log "Setting up automatic package updates..." Write-Log "Setting up automatic package updates..."
@@ -166,7 +196,7 @@ $action = New-ScheduledTaskAction -Execute "choco" -Argument "upgrade all -y --s
$trigger = New-ScheduledTaskTrigger -Daily -At "2:00AM" $trigger = New-ScheduledTaskTrigger -Daily -At "2:00AM"
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName "MABDC-AutoUpdate" -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM" -RunLevel Highest -Force | Out-Null Register-ScheduledTask -TaskName "MABDC-AutoUpdate" -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM" -RunLevel Highest -Force | Out-Null
Write-Log "Auto-update scheduled for 2:00 AM daily " Write-Log "Auto-update scheduled for 2:00 AM daily OK"
# Save join metadata # Save join metadata
$metadata = @{ $metadata = @{
@@ -177,21 +207,34 @@ $metadata = @{
windowsEdition = $edition windowsEdition = $edition
windowsVersion = [System.Environment]::OSVersion.Version.ToString() windowsVersion = [System.Environment]::OSVersion.Version.ToString()
domainName = $DomainName domainName = $DomainName
packagesInstalled = $basePackages ouPath = "OU=$Department,OU=Staff,DC=mabdc,DC=org"
status = "provisioned"
} | ConvertTo-Json -Depth 3 } | ConvertTo-Json -Depth 3
Set-Content -Path "C:\MABDC\Config\join-metadata.json" -Value $metadata -Force Set-Content -Path "C:\MABDC\Config\join-metadata.json" -Value $metadata -Force
Write-Log "" # Notify webhook
Write-Log "=========================================" Send-WebhookNotification -Data @{
Write-Log " MABDC Domain Join Complete! 🎉" event = "pc_provisioned"
Write-Log " Domain: $DomainName" pcName = $env:COMPUTERNAME
Write-Log " Department: $Department" department = $Department
Write-Log " PC Name: $env:COMPUTERNAME" domain = $DomainName
Write-Log "=========================================" status = "success"
Write-Log "" timestamp = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Write-Log "A restart is required to complete the domain join." }
$restart = Read-Host "Restart now? (Y/N)" Write-Host ""
Write-Host " =============================================" -ForegroundColor Cyan
Write-Host " MABDC Domain Join Complete!" -ForegroundColor Green
Write-Host " Domain : $DomainName" -ForegroundColor White
Write-Host " Department: $Department" -ForegroundColor White
Write-Host " PC Name : $env:COMPUTERNAME" -ForegroundColor White
Write-Host " OU : OU=$Department,OU=Staff" -ForegroundColor White
Write-Host " =============================================" -ForegroundColor Cyan
Write-Host ""
Write-Log "Provisioning complete."
$restart = Read-Host "Restart now to complete domain join? (Y/N)"
if ($restart -eq 'Y' -or $restart -eq 'y') { if ($restart -eq 'Y' -or $restart -eq 'y') {
Restart-Computer -Force Restart-Computer -Force
} }