[CmdletBinding()] param ( [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Alias("SGID")] #[ValidateNotNullOrEmpty()] [string]$SamAccountName = (Read-Host 'Entrez le GID du compte ŕ cloner') ) begin { # Clear error $error.Clear() $ErrorActionPreference = "SilentlyContinue" #$ErrorActionPreference = "Continue" #$ErrorActionPreference = "Stop" #region Help function function ScriptHelp { # Clear-Host Write-Host " " Write-Host "*************************" Write-Host " " Write-Host "Incorrect parameters !!!" -ForegroundColor Red Write-Host " " Write-Host "*************************" Write-Host " " Exit } #endregion #region Log functions function Set-ScreenLogLine { [CmdletBinding()] param ( [string]$Message = "" ) begin { } process { $D = Get-Date -Format "MM-dd-yyyy" $TimeGenerated = Get-Date -Format "HH:mm:ss.fff" $ScreenLine = "$D $TimeGenerated - $Message" return $ScreenLine } end { } } function Write-CMLog { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateScript({ Split-Path $_ -Parent | Test-Path })] [string]$FilePath, [Parameter(Mandatory = $true)] [string]$Message, [Parameter()] [ValidateSet(0, 1, 2, 3, 4)] [int]$LogLevel = 1, [Parameter(Mandatory = $false)] [switch]$Screen ) begin { Write-Verbose "********** BEGIN Write-CMLog function" } process { Write-Verbose "LogLevel : $LogLevel" switch ($LogLevel) { 0 {$LogCMLevel = 1} 1 {$LogCMLevel = 1} 2 {$LogCMLevel = 2} 3 {$LogCMLevel = 3} 4 {$LogCMLevel = 1} } $D = Get-Date -Format "MM-dd-yyyy" $ScreenLine = Set-ScreenLogLine -Message $Message $CMTimeGenerated = "$(Get-Date -Format "HH:mm:ss").$((Get-Date).Millisecond)+000" $Line = '' $LineFormat = $Message, $CMTimeGenerated, $D, ":$($MyInvocation.ScriptLineNumber)", $LogCMLevel $Line = $Line -f $LineFormat try { #"Enter Add-Content function" Add-Content -LiteralPath $FilePath -Value $Line #"End Add-Content function" if ($Screen) { switch ($LogLevel) { 0 { $Color = "Cyan" } # Information 2 { $Color = "Yellow" } # Avertissement 3 { $Color = "Red" } # Error 4 { $Color = "Green" } # Success Default { $Color = "White" } # Default } Write-Host $ScreenLine -ForegroundColor $Color } else { Write-Verbose $Message } } # process catch { # Error to write log file # Error number xx if ($Screen) { "Error Write-CMLog" Write-Error $_.Exception.Message Exit } else { # Envoyer mail Exit } } # catch } end { Write-Verbose "********** END Write-CMLog function" } } function Start-CMLog { [CmdletBinding()] param ( [ValidateScript({ Split-Path $_ -Parent | Test-Path })] [string]$FilePath ) begin { Write-Verbose "********** BEGIN Start-CMLog function" } process { try { if (!(Test-Path $FilePath)) { ## Create the log file New-Item $FilePath -Type File | Out-Null [string]$str = "Log initialized" Write-CMLog -FilePath $FilePath -Message $str Write-CMLog -FilePath $FilePath -Message "**********" } } catch { # Error to create log file # Error number xx if ($ToScreen) { "Error" Write-Error $_.Exception.Message } # envoyer mail erreur Exit } } end { Write-Verbose "********** END Start-CMLog function" } } function Add-SEContent { [CmdletBinding()] param ( [ValidateScript({ Split-Path $_ -Parent | Test-Path })] [string]$FilePath, [Parameter(Mandatory = $true)] [string]$Message ) process { # Create file if not exist try { if (!(Test-Path $FilePath)) { ## Create the file & Write message New-Item $FilePath -Type File | Out-Null [string]$str = "New file $FilePath created" Write-CMLog -FilePath $GlobalLogFile -Message $str } $Message | Out-File -FilePath $FilePath -Append [string]$str = "Message $Message added to file $FilePath" Write-CMLog -FilePath $GlobalLogFile -Message $str } # try catch { # Error to create file # Error number xx if ($ToScreen) { Write-Error $_.Exception.Message } # envoyer mail erreur Exit } # catch } # process } # Add-SEContent #endregion #region Password functions function ReverseString { param ( [string]$Str ) process { $Str_Array = $Str.ToCharArray() [array]::Reverse($Str_Array) Return -join($Str_Array) } } function GeneratePassword { param ( $length = $length ) $UpperCase = [char[]]"ABCEFGHJKLMNPQRSTUVWXYZ" $LowerCase = [char[]]"abcdefghijkmnopqrstuvwxyz" $Numbers = [char[]]"123456789" $SpecialCaracteres = [char[]]"~!@#$%^&*()-_=+[]{}<>/?" $TotalUsed = 0 [string]$password = "" while ($TotalUsed -lt $length) { if ($TotalUsed -lt $length) { $password = $password + (Get-Random $UpperCase -Count 1) $TotalUsed ++ } if ($TotalUsed -lt $length) { $password = $password + (Get-Random $LowerCase -Count 1) $TotalUsed ++ } if ($TotalUsed -lt $length) { $password = $password + (Get-Random $Numbers -Count 1) $TotalUsed ++ } if ($TotalUsed -lt $length) { $password = $password + (Get-Random $SpecialCaracteres -Count 1) $TotalUsed ++ } } $MixPassword = Get-Random $password -Count $length return $MixPassword -join "" } # #endregion #region Directory function Test-Directory { # # This function test if Directoty exist # If not, try to create it # param ( [Parameter(Mandatory = $true)] [string]$Directory ) begin { Write-CMLog -FilePath $GlobalLogFile -Message "********** BEGIN function Test-Directory" [string]$str = "Directory : $Directory" Write-CMLog -FilePath $GlobalLogFile -Message $str } process { if (-not (Test-Path $Directory)) { [string]$str = "Directory $Directory not found ! - Try to create it." Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 2 -Screen:$ToScreen try { New-Item -ItemType Directory -Path $Directory | Out-Null [string]$str = "Directory $Directory created." Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 4 -Screen:$ToScreen } catch { $StrError = $_.Exception.Message [string]$str = "Impossible to create Directory $Directory" Write-CMLog -FilePath $GlobalLogFile -Message $StrError -LogLevel 3 -Screen:$ToScreen exit } } else { [string]$str = "Directory $Directory found !" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 4 -Screen:$ToScreen } } end { Write-CMLog -FilePath $GlobalLogFile -Message "********** END function Test-Directory" } } #endregion function Test-UserMemberOf { param ( [string]$User, [string]$Group ) if ($User.IndexOf("\") -gt 0) { $Txt = $User.Split("\") $User = $Txt[1] } #Write-Host $User $Users = (Get-ADGroupMember -Server fr.green.local -Identity $Group).SamAccountName Write-Output $Users return ($Users.IndexOf($User) -gt 0) } # Is User Interactive mode (Console host) [bool]$ToScreen = [System.Environment]::UserInteractive -or ($Host.Name -eq "ConsoleHost") if ($ToScreen) { Clear-Host $str = Set-ScreenLogLine -Message "SCRIPT STARTED" Write-Host $str -ForegroundColor White } #region Verify parameters # if ("" -eq $SamAccountName) { ScriptHelp } #endregion # Script directory [string]$ScriptDirectory = Split-Path $script:MyInvocation.MyCommand.Path #region Log # Log directory [string]$LogDirectory = Join-Path -Path $ScriptDirectory -ChildPath "Logs" # Verify if Log directory exist ; if not, create it. if (-not (Test-Path -Path $LogDirectory)) { if ($ToScreen) { $str = Set-ScreenLogLine -Message "Directory $LogDirectory not found ! - Try to create it." Write-Host $str -ForegroundColor Yellow } try { New-Item -Path $LogDirectory -ItemType Directory | Out-Null if ($ToScreen) { $str = Set-ScreenLogLine -Message "Directory $LogDirectory created." Write-Host $str -ForegroundColor Green } } catch { if ($ToScreen) { $str = Set-ScreenLogLine -Message "Impossible to create Directory $LogDirectory !" Write-Host $str -ForegroundColor Red } Exit } } # Initialize log [string]$GlobalLogFile = Join-Path -Path $LogDirectory -ChildPath ("Log_MigX_{0}.log" -f (Get-Date -Format "yyyyMMdd_HHmmss")) # Start Global log file Start-CMLog ($GlobalLogFile) [string]$str = "Script Directory = $ScriptDirectory" Write-CMLog -FilePath $GlobalLogFile -Message $str [string]$str = "Log Directory = $LogDirectory" Write-CMLog -FilePath $GlobalLogFile -Message $str [string]$str = "Global log file = $GlobalLogFile" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 0 -Screen:$ToScreen # Error message [string]$StrError = "" #endregion #region Import Module AD # [string]$str = "Import module Active Directory" Write-CMLog -FilePath $GlobalLogFile -Message $str if (Get-Module -ListAvailable -Name ActiveDirectory) { try { Import-Module ActiveDirectory -Force -Verbose:$false -ErrorAction SilentlyContinue | Out-Null [string]$str = "Module Active Directory imported successfully" Write-CMLog -FilePath $GlobalLogFile -Message $str } catch { [string]$str = "Error to import module Active Directory" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 3 -Screen:$ToScreen [string]$str = "SCRIPT ENDED" Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen exit } } else { [string]$str = "Module Active Directory is not installed !" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 3 -Screen:$ToScreen [string]$str = "SCRIPT ENDED" Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen exit } #endregion # AD Domain $AD_DOMAIN = "fr.green.local" [string]$str = "AD Domain Or Domain User = $AD_Domain" Write-CMLog -FilePath $GlobalLogFile -Message $str # DC AD Domain $DC_DOMAIN = "dc=fr,dc=green,dc=local" [string]$str = "DC Domain = $DC_Domain" Write-CMLog -FilePath $GlobalLogFile -Message $str # AD AZURE #$SRV_DC_Azure = "SEFRDC01102.$AD_DOMAIN" if (-not(Test-Connection -ComputerName $AD_DOMAIN -Count 1 -ErrorAction SilentlyContinue)) { [string]$str = "Error to connect Domain Controler" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 3 -Screen:$ToScreen [string]$str = "SCRIPT ENDED" Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen exit } # Script User Name [string]$Global:ScriptUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name [string]$str = "Script executed by $Global:ScriptUserName" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 0 -Screen:$ToScreen # Group OU Migration_W10 [string]$OU_Migration_W10_Group = "GRP-SU-IT-W10-MgmtCompteMIG" [string]$str = "Group OU Migration_W10 = $OU_Migration_W10_Group" Write-CMLog -FilePath $GlobalLogFile -Message $str if (-not(Test-UserMemberOf -User $Global:ScriptUserName -Group $OU_Migration_W10_Group)) { [string]$str = "Unable to execute this script with this account" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 3 -Screen:$ToScreen [string]$str = "SCRIPT ENDED" Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen exit } #region Script Constants & Data [string]$str = "Defining constants and initializing data" Write-CMLog -FilePath $GlobalLogFile -Message $str # OU Migration W10 [string]$OU_Migration = "Migration_W10" [string]$str = "OU Migration = $OU_Migration" Write-CMLog -FilePath $GlobalLogFile -Message $str # Password length $NewPasswordLength = 8 [string]$str = "New password length = $NewPasswordLength" Write-CMLog -FilePath $GlobalLogFile -Message $str # Number of times an Account can be cloned [byte]$MAX_CLONING_ALLOWED = 20 $strMAX_CLONING_ALLOWED = $MAX_CLONING_ALLOWED.ToString() [string]$str = "Max Cloning Allowed = $strMAX_CLONING_ALLOWED" Write-CMLog -FilePath $GlobalLogFile -Message $str # Number of days for the validity of the AccountX $MAX_DAYS = 30 [string]$str = "Max Days = $MAX_DAYS" Write-CMLog -FilePath $GlobalLogFile -Message $str # AccountX Prefix $AccountPrefix = "MigX." [string]$str = "AccountX prefix = $AccountPrefix" Write-CMLog -FilePath $GlobalLogFile -Message $str # AccountX Display Name Suffix $DisplayNameSuffix = " - Migration W10" [string]$str = "AccountX Display Name Suffix = $DisplayNameSuffix" Write-CMLog -FilePath $GlobalLogFile -Message $str # Expiration Date $ExpirationDateX = (Get-Date).AddDays($MAX_DAYS) [string]$str = "Expiration Date X = $ExpirationDateX" Write-CMLog -FilePath $GlobalLogFile -Message $str #endregion #region TagUser function function TagUser([byte]$Counter, [string]$UserGID, [string]$ScriptUser){ try { $strCounter = $Counter.ToString() Set-ADUser -Server $AD_DOMAIN -Identity $userGID -Replace @{PersonalPager=$ScriptUser;Title=$strCounter} [string]$str = "PersonalPager (Script User Name) = $ScriptUser" Write-CMLog -FilePath $UserLogFile -Message $str [string]$str = "Title (Counter) = $strCounter" Write-CMLog -FilePath $UserLogFile -Message $str } catch { [string]$str = "PersonalPager (Script User Name) & Title (Counter) not updated" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 2 } } #endregion } process { function MigUserX { param ( [string]$ID_User ) begin { # Initialize log [string]$UserLogFile = Join-Path $LogDirectory -ChildPath ("Log_MigX_{0}_{1}.log" -f (Get-Date -Format "yyyyMMdd_HHmmss"), $ID_User) # Start Global log file Start-CMLog ($UserLogFile) } #begin process { #region Get Sesame Account properties [string]$str = "Get Sesame Account properties" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen # Get properties DistinguishedName, Surname, Givenname try { $UserInfos = Get-ADUser -Identity $ID_User -Server $AD_DOMAIN -Properties DistinguishedName, Surname, Givenname [string]$str = "Successfully" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen } catch { $StrError = $error[0].Exception.Message Write-CMLog -FilePath $UserLogFile -Message $StrError -LogLevel 3 -Screen:$ToScreen } #endregion if ("" -eq $StrError) { # DistinguishName $DistinguishName = $UserInfos.DistinguishedName [string]$str = "DistinguishName = $DistinguishName" Write-CMLog -FilePath $UserLogFile -Message $str # Verify if it's IT account if ($DistinguishName -like "*OU=IT,$DC_DOMAIN") { # # $StrError = "Impossible to clone : This is IT account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 3 } else { # MigX Account $SGIDX = $AccountPrefix + $ID_User [string]$str = "SAMAccountName: $SGIDX" Write-CMLog -FilePath $UserLogFile -Message $str # Cloning counter [string]$str = "Determine if MigX Account exist" Write-CMLog -FilePath $UserLogFile -Message $str try { $UserInfosX = Get-ADUser -Server $AD_DOMAIN -Identity $SGIDX -Properties * [string]$str = "MigX account $SGIDX already exist" Write-CMLog -FilePath $UserLogFile -Message $str [byte]$CountX = $UserInfosX.Title } catch { [byte]$CountX = 0 } $strCountX = $CountX.ToString() [string]$str = "CountX = $strCountX" Write-CMLog -FilePath $UserLogFile -Message $str # Test the maximum number of cloning operations if ($CountX -le $MAX_CLONING_ALLOWED) { # if number of cloning operation less or equal MAX_CLONING_ALLOWED continue #region Get AD groups from SESAME account [string]$str = "Get AD groups from SESAME account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen try { $Groups = Get-ADGroup -Server $AD_DOMAIN -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $DistinguishName) | Select-Object DistinguishedName, Name [string]$str = "$($Groups.Count) founded" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen foreach ($Group in $Groups) { [string]$str = "$($Group.Name)" Write-CMLog -FilePath $UserLogFile -Message $str } } catch { # Error to get AD Group # Write-Error $_.Exception.Error } # Lastname $LastName = $UserInfos.Surname [string]$str = "Lastname : $LastName" Write-CMLog -FilePath $UserLogFile -Message $str # Firstname $FirstName = $UserInfos.GivenName [string]$str = "Firstname : $FirstName" Write-CMLog -FilePath $UserLogFile -Message $str #endregion # Retrieve APP groups [string]$str = "Selected APP groups" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen [string]$Filter = "*GRP-SG-APP-App0*" [string]$str = "APP Filter : $Filter" Write-CMLog -FilePath $UserLogFile -Message $str $AppGroups = ($Groups | Where-Object { $_.DistinguishedName -like $Filter -and $_.DistinguishedName -notlike "OLD*" }).Name # Count AppGroups $AppGroupsCount = $AppGroups.Count #Write-CMLog -FilePath $UserLogFile -Message "Je passe bien ici" [string]$str = "$AppGroupsCount founded" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen foreach ($Group in $AppGroups) { [string]$str = "$Group" Write-CMLog -FilePath $UserLogFile -Message $str -Screen:$ToScreen } [string]$str = "Get account attributes" Write-CMLog -FilePath $UserLogFile -Message $str # MigX specifics attributes if ($SGIDX.ToString().Length -le 20) { [string]$str = "Generate MigX attributes" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen $InitialsX = "000000" [string]$str = "InitialsX: $InitialsX" Write-CMLog -FilePath $UserLogFile -Message $str $LogonNameX = "$SGIDX@$AD_DOMAIN" [string]$str = "LogonNameX: $LogonNameX" Write-CMLog -FilePath $UserLogFile -Message $str $DisplayNameX = "$FirstName $LastName ($SGIDX)" + $DisplayNameSuffix [string]$str = "DisplayNameX: $DisplayNameX" Write-CMLog -FilePath $UserLogFile -Message $str if ($DisplayNameX.length -gt 62) { $DisplayNameX = $DisplayNameX.Substring(0, 63) $str = "DisplayName too long - Get first 62 car." Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 2 [string]$str = "New DisplayNameX: $DisplayNameX" Write-CMLog -FilePath $UserLogFile -Message $str } $NameX = $DisplayNameX [string]$str = "NameX: $NameX" Write-CMLog -FilePath $UserLogFile -Message $str $DescriptionX = "COMPTE DE DEPLOIEMENT W10 de $FirstName $LastName ($SGIDX) " + $Global:ScriptUserName [string]$str = "DescriptionX: $DescriptionX" Write-CMLog -FilePath $UserLogFile -Message $str # Password $Password = GeneratePassword($NewPasswordLength) [string]$str = "Random password generated" Write-CMLog -FilePath $GlobalLogFile -Message $str $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force [string]$str = "MigX Attributes done." Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen # # Clone user # # Penser pour une version prochaine de rĂ©cupĂ©rer l'OU de l'utilisateur et de la rajouter dans la target OU # Si cette OU n'existe pas, la crĂ©er. $targetOUX = "ou=$OU_MIGRATION,ou=FR,$DC_DOMAIN" [string]$str = "Target OU Migration = $targetOUX" Write-CMLog -FilePath $UserLogFile -Message $str if ($CountX -gt 0) { try { [string]$str = "Update MigX account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen $AppGroupsX = @() # Suppression des groupes du compte Migx $GrpsX = $UserInfosX.MemberOf $NbrAppGrpXRemove = $GrpsX.Count if ($NbrAppGrpXRemove -ne 0) { foreach ($GrpX in $GrpsX) { $AppGrpx = $GrpX.split(",")[0].split("=")[1] $AppGroupsX += $AppGrpx } [string]$str = "$NbrAppGrpXRemove Groups Found" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen } Set-ADUser -Server $AD_DOMAIN -Identity $SGIDX -Initials $InitialsX -Enabled $true -Surname "$LastName" -GivenName "$FirstName" -DisplayName "$DisplayNameX" -Description "$DescriptionX" -CannotChangePassword $true [string]$str = "MigX account $SGIDX updated." Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen } catch { $StrError = $error.Exception.Message Write-CMLog -FilePath $UserLogFile -Message $StrError -LogLevel 3 -Screen:$ToScreen } try { [string]$str = "Update MigX account expiration date" Write-CMLog -FilePath $UserLogFile -Message $Str -LogLevel 0 -Screen:$ToScreen Set-ADAccountExpiration -Server $AD_DOMAIN -Identity $SGIDX -DateTime $ExpirationDateX [string]$str = "MigX account valid for $MAX_DAYS days, until $ExpirationDateX" Write-CMLog -FilePath $UserLogFile -Message $Str -LogLevel 4 -Screen:$ToScreen } catch { # # $StrError = $error.Exception.Message Write-CMLog -FilePath $UserLogFile -Message $StrError -LogLevel 3 -Screen:$ToScreen } } else { [string]$str = "Generate MigX account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen try { New-ADUser -Server $AD_DOMAIN -Initials $InitialsX -Name "$NameX" -AccountPassword $SecurePassword -Enabled $true -Path $targetOUX -UserPrincipalName "$LogonNameX" -sAMAccountName $SGIDX -Surname "$LastName" -GivenName "$FirstName" -DisplayName "$DisplayNameX" -Description "$DescriptionX" -AccountExpirationDate $ExpirationDateX -CannotChangePassword $true [string]$str = "MigX account $SGIDX valid for $MAX_DAYS days, until $ExpirationDateX" Write-CMLog -FilePath $UserLogFile -Message $Str -LogLevel 4 -Screen:$ToScreen } catch { $StrError = $error.Exception[0].Message Write-CMLog -FilePath $UserLogFile -Message $StrError -LogLevel 3 -Screen:$ToScreen } } # MigX OU [string]$str = "MigX account stored in OU $targetOUX" Write-CMLog -FilePath $UserLogFile -Message $str # Update Counter for MigX account $CountX++ TagUser -UserGID $SGIDX -Counter $CountX -ScriptUser $Global:ScriptUserName # Add APP Groups to MigX account [string]$str = "Add APP groups to MigX account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen # Compare Groups $AppGroupsCountX = 0 if (!([string]::IsNullOrEmpty($AppGroupsX))) { $Obeject = @{ ReferenceObject = $AppGroups # User account App group DifferenceObject = $AppGroupsX # Migx account App group } $compareGrp = Compare-Object @Obeject -IncludeEqual $compareGrp | Where-Object {$_.SideIndicator -eq "=="} | ForEach-Object { $Group = $_.InputObject [string]$str = "$Group APP groups match " Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen } $compareGrp | Where-Object {$_.SideIndicatore -eq "<="} | ForEach-Object { $Group = $_.InputObject [string]$str = " Add group $Group to user account $SGIDX ..." Write-CMLog -FilePath $UserLogFile -Message $str -Screen:$ToScreen try { Add-ADGroupMember -Server $AD_DOMAIN -Identity "$Group" -Members $SGIDX -ErrorAction SilentlyContinue [string]$str = "Add $Group Group to user account $SGIDX Migx !" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen $AppGroupsCountX = $AppGroupsCountX + 1 } catch { [string]$str = $error[0].Exception.Message Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 2 -Screen:$ToScreen } } $compareGrp | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object { $Group = $_.InputObject [string]$str = " Remove group $Group to user account $SGIDX ..." Write-CMLog -FilePath $UserLogFile -Message $str -Screen:$ToScreen try { Remove-ADGroupMember -Server $AD_DOMAIN -Identity "$Group" -member $SGIDX -Confirm:$false [string]$str = "$Group Remove APP groups to MigX account" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 0 -Screen:$ToScreen } catch { [string]$str = $error[0].Exception.Message Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 2 -Screen:$ToScreen } } } else { foreach ($GrpApp in $AppGroups) { [string]$str = " Add group $GrpApp to user account $SGIDX ..." Write-CMLog -FilePath $UserLogFile -Message $str -Screen:$ToScreen try { Add-ADGroupMember -Server $AD_DOMAIN -Identity "$GrpApp" -Members $SGIDX -ErrorAction SilentlyContinue [string]$str = " Added !" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen $AppGroupsCountX = $AppGroupsCountX + 1 } catch { [string]$str = $error[0].Exception.Message Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 2 -Screen:$ToScreen } } [string]$str = "$AppGroupsCountX Groups added." Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 4 -Screen:$ToScreen } try { Set-ADAccountPassword -Server $AD_DOMAIN -Identity $SGIDX -NewPassword $SecurePassword -Reset [string]$strPwdX = "Password : $Password " Write-CMLog -FilePath $UserLogFile -Message $strPwdX [string]$strSGIDX = "MigX User : $SGIDX " } catch { # Error en : Error Update password # Error fr : Erreur lors du changement de mot de passe # Error number : [string]$str = $error[0].Exception.Message Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 3 -Screen:$ToScreen } if ($ToScreen) { $NbCar = 28 [string]$BackColor = "Black" [string]$ForeColor = "White" [string]$RepeatStar = "*" * $NbCar [string]$RepeatSpace = " " * $NbCar Write-Host " " Write-Host $RepeatStar -BackgroundColor $BackColor -ForegroundColor $ForeColor Write-Host $RepeatSpace -BackgroundColor $BackColor Write-Host " $strSGIDX " -BackgroundColor $BackColor -ForegroundColor Green Write-Host $RepeatSpace -BackgroundColor $BackColor Write-Host " $strPwdX " -BackgroundColor $BackColor -ForegroundColor Green Write-Host $RepeatSpace -BackgroundColor $BackColor Write-Host $RepeatStar -BackgroundColor $BackColor -ForegroundColor $ForeColor Write-Host " " [string]$str = "User $ID_User successfully migrated to $SGIDX" Write-CMLog -FilePath $UserLogFile -Message $str Write-CMLog -FilePath $GlobalLogFile -Message $str $MigXObject = [PSCustomObject]@{ UserName = $SGIDX.ToUpper() Password = $Password FirstName = $FirstName LastName = $LastName ErrorId = 0 ErrorMessage = "" } return $MigXObject } } else { # # [string]$StrError = "New SGID too long : $SGIDX - 20 characters maximum" Write-CMLog -FilePath $UserLogFile -Message $str -LogLevel 3 -Screen:$ToScreen Write-CMLog -FilePath $GlobalLogFile -Message $StrError -LogLevel 3 $MigXObject = [PSCustomObject]@{ UserName = $SGIDX.ToUpper() Password = "" FirstName = $FirstName LastName = $LastName Error = 10 ErrorMessage = $StrError } return $MigXObject } } } } } #process end { } #end } # function MigUserX ###################################### # # SCRIPT BEGIN # ###################################### $input="y" if ("" -ne $SamAccountName) { [string]$str = "SamAccountName specified" Write-CMLog -FilePath $GlobalLogFile -Message $str $SGID = $SamAccountName.ToUpper() [string]$str = "Try to migrate $SGID..." Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen $MigX_Unitary = MigUserX -ID_User $SGID #Write-Output $MigX_Unitary } else { # No parameters [string]$str = "No parameters specified" Write-CMLog -FilePath $GlobalLogFile -Message $str -LogLevel 3 ScriptHelp } if ("" -ne $strError) { Write-CMLog -FilePath $GlobalLogFile -Message $StrError -LogLevel 3 Write-Host " " Write-Host "********************* ERROR *********************" -ForegroundColor Red Write-Host "*" -ForegroundColor Red Write-Host "* $StrError" -ForegroundColor Red Write-Host "*" -ForegroundColor Red Write-Host "********************* ERROR *********************" -ForegroundColor Red Write-Host " " } } } # process # SCRIPT ENDED # end { [string]$str = "SCRIPT ENDED" Write-CMLog -FilePath $GlobalLogFile -Message $str -Screen:$ToScreen }