# ╔════════════════════════════════════════════════════════════════════════╦═══════════════════════════╗ # ║ CREATION GUI DES COMPTES UTILISATEURS VIA CSV ( , ") ║ V1.0 ║ # ╠═════════════════════╦══════════════════════════════════════════════════╬═══════════════════════════╣ # ║ 25/04/2018 ║ by : meriadeg morel TFR IBA ║ V1.0 ║ # ╠═════════════════════╦══════════════════════════════════════════════════╬═══════════════════════════╣ # ║ 25/09/2020 ║ by : meriadeg morel TFR IBA ║ V2.0 ║ # ╚═════════════════════╩══════════════════════════════════════════════════╩═══════════════════════════╝ # Script sous licence GPLv3. # - Pour que le poste execute le script powershell executez : Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "Unrestricted" # - Executer le script de préférence sur un contrôleur du domaine # ╔═══════════════════════════════════════════════════════════════════╗ # ║ INIT AND VARS ║ # ╚═══════════════════════════════════════════════════════════════════╝ Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Application]::EnableVisualStyles() Add-Type -AssemblyName System.Drawing Add-Type -Assembly System.Web [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") #============================================================== $ErrorActionPreference="SilentlyContinue" Import-Module ActiveDirectory $DG="Domain Users" #Nomlocal du groupe active directory des utilisateurs du domaine $FullControlMember="NT AUTHORITY\SYSTEM","BUILTIN\Administrators","BUILTIN\Domain Admins" $CSVFile=$null $CENTRE1 ="GG_LAPEYROUSE_PED_APPRENANTS_LEGTA*" $CENTRE2 ="GG_LAPEYROUSE_PED_APPRENANTS_CDFA*" $CENTRE3 ="GG_LAPEYROUSE_PED_APPRENANTS_CFPPA*" $Grp ="" $OU1 ="OU=ACCOUNTS,OU=LEGTA,OU=APPRENANTS,OU=PED,OU=_LAPEYROUSE,DC=eplefpa,DC=loc" $OU2 ="OU=ACCOUNTS,OU=CDFA,OU=APPRENANTS,OU=PED,OU=_LAPEYROUSE,DC=eplefpa,DC=loc" $OU3 ="OU=ACCOUNTS,OU=CFPPA,OU=APPRENANTS,OU=PED,OU=_LAPEYROUSE,DC=eplefpa,DC=loc" $Ou ="" $HDIR="\\pdc-nas\PROFIL$\APPRENANTS\" $PR="\\pdc-nas\PROFIL$\MANDATORY\ELEVES" $HDR="P" $data= new-object System.Collections.ArrayList # ╔═══════════════════════════════════════════════════════════════════╗ # ║ FONCTIONS GLOBALES ║ # ╚═══════════════════════════════════════════════════════════════════╝ #============================================================== function MessageBox([string]$Message, [string]$WindowTitle, [System.Windows.Forms.MessageBoxButtons]$Buttons = [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]$Icon = [System.Windows.Forms.MessageBoxIcon]::None) #============================================================== { return [System.Windows.Forms.MessageBox]::Show($Message, $WindowTitle, $Buttons, $Icon) } #============================================================== function CustomInputBox([string] $title, [string] $message, [string] $defaultText) #============================================================== { $inputObject = new-object -comobject MSScriptControl.ScriptControl $inputObject.language = "vbscript" $inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) $_userInput = $inputObject.eval("getInput") return $_userInput } #============================================================== function GetErr ([boolean]$ExitOnError=$false) { #--------------------------------------------------------------------- # ExitOnError -> true = quitter le script et le dialogue lors de la detection d'erreur # false = continuer malgré l'erreur #--------------------------------------------------------------------- if ($error.Count -eq 0) { $TB_LOG.text+="...Ok`r`n" } else { if ($ExitOnError -eq $true){ $Dummy = MessageBox -Message "$($error[0])" -WindowTitle "Erreur : arrêt du script" -Buttons OK -Icon Exclamation $FORM_CleanUsersByGroups.Close() exit } else { $TB_LOG.text+=" # ERREUR:: "+$($error[0])+"`r`n" } }; $error.clear() } # Test le fonctionnement d'active directory et quitte si besoin #============================================================== function TestAD($DomainFQDN) { #============================================================== Try { (Get-ADDomain -identity $DomainFQDN).DNSRoot return $true } Catch { return $false } } #============================================================== function Remove-Diacritics ([String]$src = [String]::Empty) #============================================================== { $normalized = $src.Normalize( [Text.NormalizationForm]::FormD ) $sb = new-object Text.StringBuilder $normalized.ToCharArray() | % { if( [Globalization.CharUnicodeInfo]::GetUnicodeCategory($_) -ne [Globalization.UnicodeCategory]::NonSpacingMark) { [void]$sb.Append($_) } } Return $sb.ToString() } #============================================================== function Remove-doublespaces ([String]$src = [String]::Empty) #============================================================== { if ($src.Contains(" ")) {$src.Replace(" "," ")} if ($src.Contains(" ")) {$src.Replace(" "," ")} if ($src.Contains("--")) {$src.Replace("--","-")} if ($src.Contains("Ê")) {$src.Replace("Ê","E")} if ($src.Contains("Ë")) {$src.Replace("Ë","E")} if ($src.Contains("È")) {$src.Replace("È","E")} if ($src.Contains("É")) {$src.Replace("É","E")} if ($src.Contains("Ï")) {$src.Replace("Ï","I")} if ($src.Contains("Ù")) {$src.Replace("Ù","U")} if ($src.Contains("Ç")) {$src.Replace("Ç","C")} Return $src.ToString() } #============================================================== function PNom([string]$Nom) #============================================================== { $NText=[String]::Empty # Retrait des caract-res sp-ciaux $NText = Remove-Diacritics ($Nom) # Retrait des espace et tiret en doublon $NText = Remove-doublespaces($NText) # conversion en majuscule $NText="$NText".ToUpper() # supprimons les espaces et les particules au del- de 2 unit-es if ("$NText".Contains(" ")) { $a="$NText".split(" ") if (($a[0].Length -lt 3) -and ($a[1].Length -ge 2) ) { $NText=($a[0]+$a[1]) } else { $NText=($a[0]+$a[1].Substring(0,1)) } } # supprimons les '-'. if ("$NText".Contains("-")) { $a="$NText".split("-") $NText=($a[0]+$a[1].Substring(0,1)) } Return $NText.ToString() } #============================================================== function PPrenom([string]$PPrenom) #============================================================== { $PPText=[String]::Empty # Retrait des caract-res sp-ciaux $PPText=Remove-Diacritics ($PPrenom) # Retrait des espace et tiret en doublon $PPText = Remove-doublespaces($PPText) # conversion en majuscule $PPText="$PPText".ToUpper() # supprimons les espaces et les particules au dela de 2 unitees if ("$PPText".Contains(" ")) { $a="$PPText".split(" ") $PPText=($a[0]+$a[1].Substring(0,1)) } # supprimons les '-' if ("$PPText".Contains("-")) { $a="$PPText".split("-") $PPText=($a[0]+$a[1].Substring(0,1)) } Return $PPText.ToString() } #============================================================== function CutLongID([string]$LID) #============================================================== { $PPos=0 # Si l'identifiant dépasse les 20 caractères on raccourcis le prenom. if ($LID.Length -gt 20) { $PPos="$LID".IndexOf(".") $LID="$LID".remove(1,($PPos-2)) } # si l'identifiant est encore trops long on le coupe a 20 caractères en gardant le début. if ($LID.Length -gt 20) { $LID="$LID".Substring(0,20) } Return $LID.ToString() } #============================================================== function GenID([string]$Pre,[string]$Nom) #============================================================== { $FID=((PPrenom("$tp"))+"."+(PNom("$tn"))) $FID=(CutLongID("$FID")) Return $FID.ToString() } #============================================================== function EntryTest { #============================================================== # verify si une selection est faites et si elle n'est pas nulle ou # si nulle on desactive le bouton creer sinon on l'active $v=$CBOX_GP.SelectedItem.ToString() $c=$CBOX_GP.Items.Count $ne=$textBoxNE.text $pe=$textBoxPE.text $TID=GenID ($pe,$ne) if (($c -gt 0) -and (![System.String]::IsNullOrEmpty($v))) { $textBoxNE.enabled = $true $textBoxPE.enabled = $true if ((![System.String]::IsNullOrEmpty($ne)) -and (![System.String]::IsNullOrEmpty($pe))) { $button1.Enabled = $true } else { $button1.Enabled = $false } } $form.Refresh() } #============================================================== function SearchIfExist ([string]$ID) #============================================================== # recherche dans les identifiants si une entrée est similaire { $R = $False Foreach($e in $global:data) { if ( $e.Identifiant -eq $ID ) { $R=$True } } if ( $R ) { Return $true } else { Return $False } } #============================================================== function AddUserInList { #============================================================== $textBoxNE.Add_TextChanged($null) $textBoxPE.Add_TextChanged($null) $tp=$textBoxPE.text $tn=$textBoxNE.text $TID=(GenID "$tp" "$tn") $Bool=SearchIfExist($TID) if ( !$Bool ) { $dataGrid1.DataSource = $null $Grp=$CBOX_GP.Text $tou=$global:OU $thom=$global:HDIR $tProf=$global:PR $thd=$global:HDR $i=@([pscustomobject]@{Identifiant=$TID;Groupe=$Grp;OU=$tou;HomeDrive=$thd;HomeDir=($thom+$TID);Profil=$tProf}) $global:data.Addrange($i) $button2.enabled= $true $dataGrid1.DataSource = $global:data $textBoxPE.text="" $textBoxNE.text="" } else { MessageBox "Utilisateur déjà dans la liste !" "Attention !" } $form.Refresh() $textBoxNE.Add_TextChanged({EntryTest}) $textBoxPE.Add_TextChanged({EntryTest}) Return $true } #============================================================== function FillComboBoxs { #============================================================== #Remplir le combo des groupes $GPList=@() $CBOX_GP.Items.Clear() $CBOX_GP.Text="" $TmpGP=($global:Grp) $GPList= get-adgroup -filter {Name -like $TmpGP} $GPList|Select-Object Name foreach ($TempGP in $GPList) { $Dname=$TempGP.Name $CBOX_GP.Items.Add($Dname) } Return $true } #============================================================== function FillComboCTR { #============================================================== #Remplir le combo des classes $CBOX_CTR.Items.Clear() $CBOX_CTR.Text="" $CBOX_CTR.Items.Add($CENTRE1) $CBOX_CTR.Items.Add($CENTRE2) $CBOX_CTR.Items.Add($CENTRE3) } #============================================================== function CBCTRChg { #============================================================== # verify si une selection est faites et si elle n'est pas nulle ou # si nulle on desactive les boutons sinon on l'active et on remplit les comboboxs $v=$CBOX_CTR.SelectedItem.ToString() $c=$CBOX_CTR.Items.Count ($global:Grp)=$v if ($v){ Get-FillData FillComboBoxs $button1.Enabled = $false $CBOX_GP.Enabled = $true if ($v -eq ($global:CENTRE1)) { ($global:Ou)=$global:OU1 } if ($v -eq ($global:CENTRE2)) { ($global:Ou)=$global:OU2 } if ($v -eq ($global:CENTRE3)) { ($global:Ou)=$global:OU3 } } else { $button1.Enabled = $false $CBOX_GP.Enabled = $false } $form.Refresh() Return $true } #============================================================== function InitPC { #============================================================== #$global:CSVFile=Select-FileDialog ("Selectionnez la source de donnée") FillComboCTR $form1.refresh() } #============================================================== function RunCreate { #============================================================== $PBAR_1.value = 0 $User= whoami $User= $User.Replace("\","_") #Sauvegarder le tableau dans un fichier. $Fname= "D:\CSV-USERS\"+ $User +"_CreationEleve_" +(get-date -Format "dddd_MM-dd-yy_HHmmss") +".csv" messagebox "$Fname" "hh" #test si dejà existant [integer]$PbValue=0 [integer]$maxcnt=0 $maxcnt=$global:data.Count foreach ($Item in $global:data) { if (!$Item.Groupe.contains("!-!")){ # l'utilisateur existe t'il ? $User = Get-ADUser -LDAPFilter "(sAMAccountName=$Item.Identifiant)" If ($User -eq $Null) { # ----------------------- # non doit être créée # ----------------------- New-ADUser -ChangePasswordAtLogon $true ` -SamAccountName $Item.Identifiant ` -Name $Item.Identifiant ` -GivenName $Item.Identifiant ` -DisplayName $Item.Identifiant ` -UserPrincipalName $Item.Identifiant ` -Path $Item.OU ` -ProfilePath $Item.Profil ` -HomeDrive $Item.HomeDrive ` -HomeDirectory $Item.HomeDir ` -AccountPassword (ConvertTo-SecureString -AsPlainText “Temp” -Force ) ` -Enabled $true } write-host $Item # ----------------------- # Oui, juste mettre à jour le groupe # ----------------------- # Clean all groups from user memberships Get-ADUser -Identity $Item.Identifiant -Properties MemberOf | ForEach-Object { $_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false } # Add needed groups Add-ADGroupMember -Identity $Item.Groupe –Member $Item.Identifiant #Add-ADGroupMember -Identity $DG –Member $Account #------------------------------------- # PREPARATION DU DOSSIER UTILISATEUR #------------------------------------- # existe t'il ? if (-not (Test-Path $Item.HomeDir)) { # non il n'existe pas, on le creer New-Item -ItemType directory -Path ($Item.HomeDir)|Out-Null } $HomeFolderACL=Get-Acl $Item.HomeDir $HomeFolderACL.SetAccessRuleProtection($true,$false) #set acl to folder $FCList=($global:FullControlMember+$Item.Identifiant) $FCList|ForEach-Object { $ACL=New-Object System.Security.AccessControl.FileSystemAccessRule($_,"FullControl","ContainerInherit,ObjectInherit","None","Allow")# $HomeFolderACL.AddAccessRule($ACL) } Set-Acl -Path $Item.HomeDir $HomeFolderACL $Item | Add-Member -MemberType NoteProperty -Name "Crée" -Value "Oui" $PbValue++ $PBAR_1.value = (100/$maxcnt*$PbValue) }} $global:data | Export-Csv -Path $Fname #ConvertTo-Csv -NoTypeInformation | Out-file "D:\CSV-USERS\$Fname" MessageBox "Création des comptees et dossiers terminé `r`n Fichier CSV mis a jour" "FINI" } function GenerateForm { ######################################################################## # Generated On: 8/29/2018 11:38 AM # Generated By: MOREL MERIADEG ######################################################################## $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState # ╔═══════════════════════════════════════════════════════════════════╗ # ║ CREATION DES FORMULAIRES ║ # ╚═══════════════════════════════════════════════════════════════════╝ # # FORMULAIRE # ════════════════════════════════════════════ $form1 = New-Object System.Windows.Forms.Form $form1.Text = "CREER UN COMPTE ELEVE" $form1.Name = "form1" $form1.width = 620 $form1.Height = 500 $form1.DataBindings.DefaultDataSourceUpdateMode = 0 $form1.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog; $form1.topmost = $true ### LABEL CHOIX CENTRE # ════════════════════ $label0 = New-Object System.Windows.Forms.Label $label0.Width = 80 $label0.Height = 23 $label0.Text = "CENTRE=" $label0.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,2,3,0) $label0.ForeColor = [System.Drawing.Color]::FromArgb(255,0,102,204) $label0.DataBindings.DefaultDataSourceUpdateMode = 0 $label0.Name = "label1" $label0.Location = New-Object System.Drawing.Point(13,15) ### COMBOBOX CHOIX CENTRE # ══════════════════════════ $CBOX_CTR = New-Object system.Windows.Forms.ComboBox $CBOX_CTR.text = "" $CBOX_CTR.width = 500 $CBOX_CTR.height = 50 $CBOX_CTR.location = New-Object System.Drawing.Point(100,15) $CBOX_CTR.Font = 'Microsoft Sans Serif,8' $CBOX_CTR.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList; $CBOX_CTR.Sorted = $True ### LABEL COMBOBOX GROUPE CLASSE # ════════════════════════════════ $labelcc = New-Object System.Windows.Forms.Label $labelcc.AutoSize = $True $labelcc.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,2,3,0) $labelcc.Text = "GROUPE DE CLASSE :" $labelcc.ForeColor = 'Black' $labelcc.Visible = $true $labelcc.Enabled = $false $labelcc.Location = New-Object System.Drawing.Point(50,80) ### COMBOBOX CHOIX GROUPE CLASSE # ════════════════════════════════ $CBOX_GP = New-Object system.Windows.Forms.ComboBox $CBOX_GP.text = "" $CBOX_GP.width = 382 $CBOX_GP.height = 50 $CBOX_GP.location = New-Object System.Drawing.Point(220,80) $CBOX_GP.Font = 'Microsoft Sans Serif,8' $CBOX_GP.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList; $CBOX_GP.Sorted = $True $CBOX_GP.Enabled = $false ### LABEL NOMS ELEVE # ════════════════════════════════ $label1 = New-Object System.Windows.Forms.Label $label1.AutoSize = $True $label1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,2,3,0) $label1.Text = "Nom complet de l'élève :" $label1.ForeColor = 'Black' $label1.Visible = $true $label1.Enabled = $false $label1.Location = New-Object System.Drawing.Point(50,120) ### TEXTBOX NOM ELEVE # ════════════════════════════════ $textBoxNE = New-Object System.Windows.Forms.TextBox $textBoxNE.Location = New-Object System.Drawing.Point(220,120) ### Location of the text box $textBoxNE.Size = New-Object System.Drawing.Size(300,30) ### Size of the text box $textBoxNE.Multiline = $False $textboxNE.AcceptsReturn = $False $textBoxNE.ScrollBars = "None" $textBoxNE.Visible = $true $textBoxNE.Enabled = $false ### LABEL PRENOMS ELEVE # ════════════════════════════════ $label2 = New-Object System.Windows.Forms.Label $label2.AutoSize = $True $label2.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,2,3,0) $label2.Text = "Prénoms de l'élève :" $label2.ForeColor = 'Black' $label2.Visible = $true $label2.Enabled = $false $label2.Location = New-Object System.Drawing.Point(50,150) ### TEXTBOX PRENOM ELEVE # ════════════════════════════════ $textBoxPE = New-Object System.Windows.Forms.TextBox $textBoxPE.Location = New-Object System.Drawing.Point(220,150) ### Location of the text box $textBoxPE.Size = New-Object System.Drawing.Size(300,30) ### Size of the text box $textBoxPE.Multiline = $False $textboxPE.AcceptsReturn = $False $textBoxPE.ScrollBars = "None" $textBoxPE.Visible = $true $textBoxPE.Enabled = $false ### BOUTON AJOUTER # ════════════════════════════════ $button1 = New-Object System.Windows.Forms.Button $button1.Name = "button1" $button1.Width = 550 $button1.Height = 23 $button1.UseVisualStyleBackColor = $True $button1.Text = "AJOUTER ELEVE A LA LISTE DE CREATION" $button1.DataBindings.DefaultDataSourceUpdateMode = 0 $button1.Location = New-Object System.Drawing.Point (50,190) $button1.Enabled = $false ### PROGRESSBAR in CREATION # ══════════════════════════ $PBAR_1 = New-Object system.Windows.Forms.ProgressBar $PBAR_1.BackColor = "#14274d" $PBAR_1.width = 550 $PBAR_1.height = 10 $PBAR_1.location = New-Object System.Drawing.Point(50,220) ### DATAGRID FOR CREATION RESULTS # ═════════════════════════════════ $dataGrid1 = New-Object System.Windows.Forms.DataGrid $dataGrid1.Width = 550 $dataGrid1.Height = 200 $dataGrid1.DataBindings.DefaultDataSourceUpdateMode = 0 $dataGrid1.HeaderForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0) $dataGrid1.Name = "$dataGrid1" $dataGrid1.DataMember = "" #$dataGrid1.TabIndex = 0 $dataGrid1.readonly=$true $dataGrid1.Location = New-Object System.Drawing.Point (50,230) $dataGrid1.RowHeadersVisible = $true $dataGrid1.AllowUserToAddRows = $false $dataGrid1.AllowUserToDeleteRows = $false $dataGrid1.SelectionMode = 2 $dataGrid1.MultiSelect = $false ### BOUTON CREER # ════════════════════════════════ $button2 = New-Object System.Windows.Forms.Button $button2.Name = "button2" $button2.Width = 550 $button2.Height = 30 $button2.UseVisualStyleBackColor = $True $button2.Text = "CREER LES COMPTES CI DESSUS" $button2.DataBindings.DefaultDataSourceUpdateMode = 0 $button2.Location = New-Object System.Drawing.Point (50,430) $button2.Enabled = $false #Save the initial state of the form $form1.controls.AddRange(@($label0,$label1,$textBoxNE,$label2,$textBoxPE,$CBOX_CTR,$button1,$dataGrid1,$buttondel,$labelcc,$CBOX_GP,$PBAR_1,$CBOX_CL,$button2)) $InitialFormWindowState = $form1.WindowState # ╔═══════════════════════════════════════════════════════════════════╗ # ║ PROCEDURE EVENT GUI ║ # ╚═══════════════════════════════════════════════════════════════════╝ $form1.add_Load({ InitPC }) $CBOX_CTR.add_SelectedIndexChanged({CBCTRChg}) $CBOX_GP.add_SelectedIndexChanged({EntryTest}) $button1.add_Click({AddUserInList}) $button2.add_Click({RunCreate}) $textBoxNE.Add_TextChanged({EntryTest}) $textBoxPE.Add_TextChanged({EntryTest}) #Show the Form $form1.ShowDialog()| Out-Null } #End Function # ╔═══════════════════════════════════════════════════════════════════╗ # ║ MAIN ║ # ╚═══════════════════════════════════════════════════════════════════╝ if (testAD "DC=eplefpa,DC=loc") { GenerateForm } else { $Dummy = MessageBox -Message "Le poste de travail n'est pas intégré au domaine `r`n Ce script s'execute sur un serveur AD..." -WindowTitle "Erreur" -Buttons OK -Icon Exclamation }