Overblog
Editer l'article Suivre ce blog Administration + Créer mon blog

PS1 Perso Functions

Publié le par damcuvelier

# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Début des scripts:
# $erroractionpreference = 'silentlycontinue'
# Set-ExecutionPolicy bypass -force
# $scriptpath = split-path -parent $MyInvocation.MyCommand.Path

# # Get Fonctions & Variables
# . $scriptpath\Functions.ps1

# Start-Transcript -Path $LogFileFullName -Append -IncludeInvocationHeader
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Fin des scripts:
# Stop-Transcript
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
param($Country,[switch]$tst,[switch]$Build)
$global:ContractorClient = '<client name>'
$global:FQDN = '<client domain FQDN>'
$global:MDTCENTRALNAME = '<client domain FQDN>'

$erroractionpreference = 'silentlycontinue'
Set-ExecutionPolicy bypass -force
$scriptpath = split-path -parent $MyInvocation.MyCommand.Path
[System.Collections.ArrayList]$CountryList = @()
[System.Collections.ArrayList]$MDTPaths = @()
$Global:computername = $env:computername
$global:Prod = $true
$scriptname = $MyInvocation.MyCommand.Name
$here = (Get-Location).path
$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$TSEnvironments = (Get-ChildItem TSEnv:)
$TSEnvironmentList = (Get-ChildItem TSEnvList:)
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | out-null

##################################################### Functions ###################
############################## Global Variables ##############################
$Global:MDTDSshareName = 'MDTProduction$'

if($Build){$global:DSCentral = "F:\INTERNATIONAL\Clone\Template"}else{
if($Prod){$Global:DSCentral = (Get-SmbShare | where-object{$_.Name -match 'MDTProduction'}).Path}
if(!$Prod){$global:DSCentral = "F:\INTERNATIONAL\Clone\Template"}    
}
$Global:drive = Split-Path -Path $scriptpath -Qualifier
$Global:root = split-path -parent $scriptpath
$global:SyncTagFile = "$DSCentral\sync.txt"

############################## Global Structure Variables
$Global:FTPPath = "$drive\MDTBootMedia"
$Global:rootBootMedia = "$root\BootMedia"
$Global:rootControls = "$root\Controls"
$Global:rootlogs = "$root\logs"
$Global:rootMDTCountry = "$root\MDTCountry"
$Global:rootScripts = $scriptpath
# $Global:rootScripts = "$root\Scripts"
$Global:TemplateMDT = "$root\Template"
$Global:MDTBootMediaPath = "$drive\MDTBootMedia"
$struct = @($FTPPath,$rootBootMedia,$rootControls,$rootlogs,$rootMDTCountry,$TemplateMDT)
$struct.split(",") | foreach{if(!(test-path $_)){cmd /c "md $_ 2>&1" | out-null}}

############################## Others Global Variables
$Global:LPsource = "$DSCentral\Applications\ForceLP"
$Global:InfosLPcsvfile = "$LPsource\InfosLP.csv"
if(!(test-path $InfosLPcsvfile)){$Global:InfosLPcsvfile = "$rootScripts\InfosLP.csv"}
$Global:LPInfosCSVs = Import-CSV -Path $InfosLPcsvfile -Delimiter ";"
$Global:chr = [char]34
if(! $TargetMDT){$TargetMDT = $LPInfosCSVs | foreach{if($_.Pays -match $Country){$_.MDTSRV}}}
if(! $Site){$Site = $LPInfosCSVs | foreach{if($_.Pays -match $Country){$_.Site}}}
# if(! $CTRLCountry){$CTRLCountry = "$rootMDTCountry\$Country\Control"}

############ Variables for Watching:
# [int]$Global:starttimejob = 08
[int]$Global:starttimejob = "21:00:00"
# [int]$Global:endtimejob = 21
[int]$Global:DbtHNO = 19
[int]$Global:watchtiming = 30
$Global:timeout = $watchtiming * 1000
$global:today = (Get-Date).Date
$global:stdtoday = (Get-Date -format "yyyyMMdd HHmmss")
$global:Stringtoday = $today.ToString("yyyyMMdd")
$global:surveylog = "$rootlogs\surveylog"
if(!(test-path $surveylog)){cmd /c "md $surveylog"}
[int]$global:i = 1

############ Variables for Logs:
# $TranscriptLogFile = "$rootlogs\Transcript_$Country" + "_$Stringtoday" + '.log'
# $CountryLogFileGlobal = "$rootlogs\Cloning_$Country" + '_' + $Site + '.log'

############################## FUNCTIONS ##############################
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | out-null
function msgbox($value){
    $erroractionpreference = 'silentlycontinue'
[System.Windows.Forms.MessageBox]::Show($value,'WARNING')
}

function logorhost($val){
    if(! $Country){$Country = $LPInfosCSVs | foreach{if($_.Site -match $Site){$_.Pays}}}
    $CountryLogFileGlobal = "$rootlogs\Cloning_$Country" + '_' + $Site + '.log'
    write-host $val
    $stdtoday + ' : ' + $val | out-file $CountryLogFileGlobal -append -Encoding ascii -Force
}

function getToolsPaths{
[string]$Arch = $Env:PROCESSOR_ARCHITECTURE
[String]$MDTInstall = ((Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Deployment 4').Install_Dir)
[String]$InstalledWindowsKits32 = ((Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots').KitsRoot10)
[String]$InstalledWindowsKits64 = ((Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots').KitsRoot10)

if($Arch -match "64"){$KitsRoot10 = $InstalledWindowsKits64}else{$KitsRoot10 = $InstalledWindowsKits32}

$AdkRoot = Join-Path $KitsRoot10 'Assessment and Deployment Kit'
$WinPERoot = Join-Path $AdkRoot 'Windows Preinstallation Environment'

$PathDeploymentTools = Join-Path $AdkRoot (Join-Path 'Deployment Tools' $Arch)
$PathWinPE = Join-Path $WinPERoot $Arch
    
$MDTModFullName = $MDTInstall + 'Bin\MicrosoftDeploymentToolkit.psd1'
$BootOrder = $MDTInstall + 'Templates\BootOrder.txt'
$KitsRoot = $KitsRoot10
$AdkRoot = $AdkRoot
$PathBCDBoot = Join-Path $PathDeploymentTools 'BCDBoot'
# $PathDeploymentTools = $PathDeploymentTools
$PathDISM = Join-Path $PathDeploymentTools 'DISM'
$PathOscdimg = Join-Path $PathDeploymentTools 'Oscdimg'
$PathUsmt = Join-Path $AdkRoot (Join-Path 'User State Migration Tool' $Arch)
$PathWinPE = Join-Path $WinPERoot $Arch
$PathWinPEMedia = Join-Path $PathWinPE 'Media'
$PathWinSetup = Join-Path $AdkRoot (Join-Path 'Windows Setup' $Arch)
$WinPEOCs = Join-Path $PathWinPE 'WinPE_OCs'
$WinPERoot = $WinPERoot
$WimSourcePath = Join-Path $PathWinPE 'en-us\winpe.wim'
$bcdbootexe = Join-Path $PathDeploymentTools (Join-Path 'BCDBoot' 'bcdboot.exe')
$bcdeditexe = Join-Path $PathDeploymentTools (Join-Path 'BCDBoot' 'bcdedit.exe')
$bootsectexe = Join-Path $PathDeploymentTools (Join-Path 'BCDBoot' 'bootsect.exe')
$dismexe = Join-Path $PathDeploymentTools (Join-Path 'DISM' 'bootsect.exe')
$efisysbin = Join-Path $PathDeploymentTools (Join-Path 'Oscdimg' 'efisys.bin')
$efisysnopromptbin = Join-Path $PathDeploymentTools (Join-Path 'Oscdimg' 'efisys_noprompt.bin')
$etfsbootcom = Join-Path $PathDeploymentTools (Join-Path 'Oscdimg' 'etfsboot.com')
$imagexexe = Join-Path $PathDeploymentTools (Join-Path 'DISM' 'imagex.exe')
$oa3toolexe = Join-Path $PathDeploymentTools (Join-Path 'Licensing\OA30' 'oa3tool.exe')
$oscdimgexe = Join-Path $PathDeploymentTools (Join-Path 'Oscdimg' 'oscdimg.exe')
$pkgmgrexe = Join-Path $PathDeploymentTools (Join-Path 'DISM' 'pkgmgr.exe')

$MDTPaths = "$MDTModFullName;$BootOrder;$KitsRoot;$AdkRoot;$PathBCDBoot;$PathDeploymentTools;$PathDISM;$PathOscdimg;$PathUsmt;$PathWinPE;$PathWinPEMedia;$PathWinSetup;$WinPEOCs;$WinPERoot;$WimSourcePath;$bcdbootexe;$bcdeditexe;$bootsectexe;$dismexe;$efisysbin;$efisysnopromptbin;$etfsbootcom;$imagexexe;$oa3toolexe;$oscdimgexe;$pkgmgrexe"

Return $MDTPaths
}
$ToolsPaths = getToolsPaths
$Global:MDTMod = $ToolsPaths.split(";")[0]
$Global:OSCDIMG = $ToolsPaths.split(";")[24]
$Global:etfsboot = $ToolsPaths.split(";")[21]
$Global:efisysbin = $ToolsPaths.split(";")[19]
$Global:BootOrder = $ToolsPaths.split(";")[1]

function getvalues{
param($Country,$Site)
    $LPInfosCSVs | foreach{
        if(($_.Pays -match $Country)-and ($_.Site -match $Site)){
        $langcode = $_.LocalLangCode
        $Keyboard = $_.LocalKeyb
        $DefLangCode = $_.DefLangCode
        $DefKeyb = $_.DefKeyb
        $TimeZone = $_.TimeZoneCode
        $TimeZoneName = $_.TimeZoneName
        $MDTSRV = $_.MDTSRV
        $Site = $_.Site
        }
    }

if(! (test-path "$LPsource\Microsoft-Windows-Client-language-Pack_x64_$Langcode.cab")){$Langcode = $DefLangCode; $Keyboard = $DefKeyb}
if((! $MDTSRV) -or ($MDTSRV -eq "")){$MDTSRV = "USBKEY"}
$getvalues = "$Country;$langcode;$Keyboard;$TimeZone;$TimeZoneName;$MDTSRV;$Site"

return $getvalues
}

function getcsvalue{
    param($variable,$Template,$CSfile)
    if(! $CSfile){$CSfile = "$Template\Customsettings.ini"}
    $BSfile = $CSfile.replace("Customsettings.ini","Bootstrap.ini")
    (Get-Content $CSfile) | ForEach {if($_ -notmatch ";"){
        if(($_ -match $variable) -and ($_ -match "=") -and ($_ -notmatch "Skip") -and ($_ -notmatch ";")){$getcsvalue = $_.split("=")[1]}}
    }
    if(! $getcsvalue){
        (Get-Content $BSfile) | ForEach {if($_ -notmatch ";"){
            if(($_ -match $variable) -and ($_ -match "=") -and ($_ -notmatch "Skip") -and ($_ -notmatch ";")){$getcsvalue = $_.split("=")[1]}}
        }
    }
return $getcsvalue
}

function chglg{
    param($Country,$MDTCountry,$Site)
$values = getvalues -Country $Country -Site $Site
write-host "values = $values"
$langcode = $values.split(";")[1]
$Keyboard = $values.split(";")[2]
$TimeZone = $values.split(";")[3]
$TimeZoneName = $values.split(";")[4]
$MDTSRV = $values.split(";")[5]
$Site = $values.split(";")[6]

$syncMDT = $LPInfosCSVs | foreach{if($_.Pays -match $Country){$_.syncMDT}}
# if($syncMDT -eq "YES"){

# if($MDTSRV -eq "USBKEY"){$MDTCountry = "$rootMDTCountry\Media_$Country\Content\Deploy"}else{$MDTCountry = "$rootMDTCountry\MDT_$Country"}
$ctrls = "$MDTCountry\Control"

logorhost("chglg for Control-$Country")
# if($Country -match " "){$ctrls = $chr + "$rootControls\Control_$Country" + $chr}else{$ctrls = "$rootControls\Control_$Country"}

# $ctrls = "$rootControls\Control_$fldrCountry"
# if(!(test-path $ctrls)){cmd /c "md $ctrls" | out-null}
$oldMDTSRV = getcsvalue -Template "$DSCentral\Control" -variable "MDTSRV="

    foreach($file in get-childitem -path $ctrls -recurse){
    $filefullname = $file.fullname
        if(($filefullname -match ".ini") -or ($filefullname -match ".xml")){
        if(($filefullname -eq "Bootstrap.ini") -or ($filefullname -eq "CustomSettings.ini")){
            if($MDTSRV -ne "USBKEY"){
            (Get-Content $filefullname) | ForEach {$_ -replace "$oldMDTSRV.$FQDN","$MDTSRV.$FQDN"} | Set-Content $filefullname
            (Get-Content $filefullname) | ForEach {$_ -replace "$oldMDTSRV",$MDTSRV} | Set-Content $filefullname
            (Get-Content $filefullname) | ForEach {$_ -replace $MDTSRV,"$MDTSRV.$FQDN"} | Set-Content $filefullname
        }
        if($MDTSRV -eq "USBKEY"){"DEPLOYMENTMETHOD=Media" | out-file $filefullname -Append -Encoding ascii -Force }
        }}
        (Get-Content $filefullname) | ForEach {$_ -replace "fr-fr",$langcode} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "%langcode%",$langcode} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "TimeZone=105","TimeZone=$TimeZone"} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "%TimeZone%",$TimeZone} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "Romance Standard Time",$TimeZoneName} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "France",$Country} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "040C:0000040C",$Keyboard} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace "WSUSServer=","; WSUSServer="} | Set-Content $filefullname
            
        (Get-Content $filefullname) | ForEach {$_ -replace "; ; ","; "} | Set-Content $filefullname
        (Get-Content $filefullname) | ForEach {$_ -replace ".$FQDN.$FQDN",".$FQDN"} | Set-Content $filefullname
    
        }
    }
    # for monitoring on DSCentral:
    (Get-Content "$ctrls\CustomSettings.ini") | ForEach {$_ -replace "EventService=http://$MDTSRV","EventService=http://$MDTCENTRALNAME"} | Set-Content "$ctrls\CustomSettings.ini"
    (Get-Content "$ctrls\CustomSettings.ini") | ForEach {$_ -replace "WSUSServer=http://$MDTSRV","WSUSServer=http://$MDTCENTRALNAME"} | Set-Content "$ctrls\CustomSettings.ini"
    Bootstrap
    # for usbkey (=! MDT Server):
    if($MDTSRV -eq "USBKEY"){
        cmd /c "COPY /Y $ctrls\MedBootstrap.ini $ctrls\Bootstrap.ini" | out-null
        cmd /c "COPY /Y $ctrls\MedCustomSettings.ini $ctrls\CustomSettings.ini" | out-null
    }
    
return $ctrls
# }
}

function getfreedrive{
    $PSDriveNames = (Get-PSDrive -PSProvider filesystem).Name
$mappeds = (Get-ChildItem -Path HKCU:\Network\).Name.replace("HKEY_CURRENT_USER\Network\","")
foreach($mapped in $mappeds){
    $mapdrive = $mapped.replace("HKEY_CURRENT_USER\Network\","")
    if($PSDriveNames -notcontains $mapdrive){$PSDriveNames += $mapdrive}
}
$drvlist=$PSDriveNames
# $drvlist=(Get-PSDrive -PSProvider filesystem).Name
Foreach ($drvletter in "HIJKLMNOPQRST".ToCharArray()) {
    If ($drvlist -notcontains $drvletter) {
        return $drvletter
        break
    }
}
}

function getLPInfosCSVVars{
    param($Template,$LPInfoCSVFile,$Country)
[System.Collections.ArrayList]$LPInfos = @()
$LPInfosCSV = Import-CSV -Path $LPInfoCSVFile -Delimiter ";"
foreach($LPInfoCSV in $LPInfosCSV){
    if(($LPInfoCSV.Pays).replace(" ","") -match ($Country).replace(" ","")){
$UserDomain = $LPInfoCSV.Domain
$UserID = $LPInfoCSV.User
# $UserPassword = $LPInfoCSV.Password
$Langcode = $LPInfoCSV.LocalLangCode
$DefLangCode = $LPInfoCSV.DefLangCode
$Keyboard = $LPInfoCSV.LocalKeyb
$DefKeyb = $LPInfoCSV.DefKeyb
$TimeZone = $LPInfoCSV.TimeZoneCode
$TimeZoneName = $LPInfoCSV.TimeZoneName
$MDTSRV = $LPInfoCSV.MDTSRV
if(! $TargetMDT){$TargetMDT = $MDTSRV}
if(! $TargetMDTPath){$TargetMDTPath = $LPInfoCSV.Path}
if(! $MDTShareName){$MDTShareName = $LPInfoCSV.MDTShareName}
break
}}
if((! $MDTShareName) -or ($MDTShareName -eq "")){$MDTShareName = $MdtshareNameSource}
if(test-path "$Template\Applications\ForceLP"){$LPsource = "$Template\Applications\ForceLP"}else{$LPsource = "$scriptpath\LIPContent"}
if(! (test-path "$LPsource\Microsoft-Windows-Client-language-Pack_x64_$Langcode.cab")){$Langcode = $DefLangCode; $Keyboard = $DefKeyb}

if(! $TargetMDT){$TargetMDT = "N/A"}
if(! $TargetMDTPath){$TargetMDTPath = "N/A"}
if(! $TSName){$TSName = getcsvalue -Template "$Template\control" -variable "TASKSEQUENCEID"}
if(! $UserID){$UserID =getcsvalue -Template "$Template\control" -variable "UserID"}
# if(! $UserPassword){$UserPassword =getcsvalue -Template "$Template\control" -variable "UserPassword"}
if(! $UserDomain){$UserDomain =getcsvalue -Template "$Template\control" -variable "UserDomain"}

$result = "$Country;$Langcode;$Keyboard;$TimeZone;$TimeZoneName;$UserID;$UserDomain;$TSName;$TargetMDT;$TargetMDTPath;$MDTShareName;$MDTSRV"
return $result
}

function updtWinPE{
    param($MDTPath,[switch]$tst)
logorhost("update winpe boot file from $MDTPath")

$WinPE_OCsPath = "F:\sys\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs"
$cabs = @("$WinPE_OCsPath\WinPE-hta.cab","$WinPE_OCsPath\WinPE-scripting.cab","$WinPE_OCsPath\WinPE-wmi.cab","$WinPE_OCsPath\WinPE-netfx.cab","$WinPE_OCsPath\WinPE-powershell.cab","$WinPE_OCsPath\WinPE-dismcmdlets.cab","$WinPE_OCsPath\WinPE-storagewmi.cab","$WinPE_OCsPath\WinPE-enhancedstorage.cab","$WinPE_OCsPath\WinPE-securebootcmdlets.cab","$WinPE_OCsPath\WinPE-securestartup.cab")

$winpeboot = "$MDTPath\Boot"
$wim = "$winpeboot\LiteTouchPE_x64.wim"
$mount = "$winpeboot\mount"
cmd /c "md $mount"
cmd /c "Dism /Unmount-Image /MountDir:$mount /discard 2>&1" | out-null
cmd /c "Dism /Mount-Image /ImageFile:$wim /Index:1 /MountDir:$mount"
if($tst){
logorhost("add winpe features")
foreach($cab in $cabs.split(",")){if(test-path $cab){Dism /image:$mount /add-package /packagepath:$cab}}
}
cmd /c "copy /Y $MDTPath\Scripts\readmdtsrv.vbs $mount\deploy\scripts"
cmd /c "copy /Y $MDTPath\Scripts\LiteTouch.wsf $mount\deploy\scripts"
cmd /c "Dism /Unmount-Image /MountDir:$mount /commit"
cmd /c "rmdir /S /Q $mount"
}

function updtWinPEBootMedia{
    param($MDTPath,$Country,$Site)
logorhost("update winpe boot file from $MDTPath")

$WinPE_OCsPath = "F:\sys\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs"
$cabs = @("$WinPE_OCsPath\WinPE-hta.cab","$WinPE_OCsPath\WinPE-scripting.cab","$WinPE_OCsPath\WinPE-wmi.cab","$WinPE_OCsPath\WinPE-netfx.cab","$WinPE_OCsPath\WinPE-powershell.cab","$WinPE_OCsPath\WinPE-dismcmdlets.cab","$WinPE_OCsPath\WinPE-storagewmi.cab","$WinPE_OCsPath\WinPE-enhancedstorage.cab","$WinPE_OCsPath\WinPE-securebootcmdlets.cab","$WinPE_OCsPath\WinPE-securestartup.cab")
$csvvalues = getvalues -Country $Country -Site $Site
$keyboard = $csvvalues.split(";")[2]
$keyb = "0409:00000409"
if($keyboard -eq "040c:0000040c"){$keyb = $keyboard}

$winpeboot = "$MDTPath\Boot"
$wim = "$winpeboot\LiteTouchPE_x64.wim"
$mount = "$winpeboot\mount"
cmd /c "md $mount"
cmd /c "Dism /Unmount-Image /MountDir:$mount /discard 2>&1" | out-null
cmd /c "Dism /Mount-Image /ImageFile:$wim /Index:1 /MountDir:$mount"

cmd /c "copy /Y $MDTPath\Scripts\readmdtsrv.vbs $mount\deploy\scripts"
"wscritp.quit" | out-file "$mount\deploy\Scripts\readmdtsrv.vbs" -Encoding ascii -Force

cmd /c "copy /Y $MDTPath\Scripts\MedLiteTouch.wsf $mount\deploy\scripts\LiteTouch.wsf"
cmd /c "copy /Y $MDTPath\Control\MedBootStrap.ini $MDTPath\Control\BootStrap.ini"
cmd /c "copy /Y $MDTPath\Control\MedBootStrap.ini $mount\deploy\scripts\BootStrap.ini"
# "[Settings]" | out-file "$mount\deploy\scripts\BootStrap.ini" -Encoding ascii -Force
# "Priority=Default" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# " " | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# "[Default]" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# "SkipBDDWelcome=YES" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# "KeyBoardInputLocalePE=$keyb" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# "KeyBoardLocalePE=$keyb" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
# "KeyBoardLocale=$keyb" | out-file "$mount\deploy\scripts\BootStrap.ini" -append -Encoding ascii -Force
cmd /c "Dism /Unmount-Image /MountDir:$mount /commit"
cmd /c "rmdir /S /Q $mount"
}

function createctrlcountry{
    param($Country,$MDTSRV,$Site,[switch]$tst)
    $chr = [char]39
# $DSCentral = "F:\DSLocal_France"
# $MDTCountry = "F:\INTERNATIONAL\Clone\MDTCountry\Media_FranceParis-Iena\Content\Deploy"
$CTRLDSCentral = "$DSCentral\Control"
if($MDTSRV -eq "USBKEY"){
    $BootStrapini = "MedBootStrap.ini"
    $CustomSettingsini = "MedCustomSettings.ini"
    $MDTCountry = "$rootMDTCountry\Media_$Country$Site\Content\Deploy"}else{
    $BootStrapini = "BootStrap.ini"
    $CustomSettingsini = "CustomSettings.ini"
    $MDTCountry = "$rootMDTCountry\MDT_$Country$Site"
    }

$CTRLCountry = "$MDTCountry\Control"
# if(!(test-path $CTRLCountry)){
    # cmd /c "md $CTRLCountry 2>&1" | out-null
    # cmd /c "ROBOCOPY /E $CTRLDSCentral $CTRLCountry"
# }

# $CTRLDSCentralLastWriteTime = (get-item $CTRLDSCentral).LastWriteTime.Date
# $CTRLMDTCountryLastWriteTime = (get-item $CTRLCountry).LastWriteTime.Date

# if($CTRLDSCentralLastWriteTime -ne $CTRLMDTCountryLastWriteTime){
    # cmd /c "rmdir /S /Q $CTRLCountry"
    # cmd /c "ROBOCOPY /E $CTRLDSCentral $CTRLCountry"
    # cmd /c "copy /Y $CTRLDSCentral\$BootStrapini $CTRLCountry\BootStrap.ini"
    # cmd /c "copy /Y $CTRLDSCentral\$CustomSettingsini $CTRLCountry\CustomSettings.ini"
    # cmd /c "copy /Y $DSCentral\Scripts\$LiteTouchwsf $MDTCountry\Scripts\LiteTouch.wsf"
# }
        
if(test-path $CTRLCountry){cmd /c "rmdir /S /Q $CTRLCountry"}
    cmd /c "md $CTRLCountry"
    cmd /c "ROBOCOPY /E $CTRLDSCentral $CTRLCountry"
    cmd /c "copy /Y $CTRLDSCentral\$BootStrapini $CTRLCountry\BootStrap.ini"
    cmd /c "copy /Y $CTRLDSCentral\$CustomSettingsini $CTRLCountry\CustomSettings.ini"


chglg -Country $Country -MDTCountry $MDTCountry -Site $Site

}

function SyncCtrlFldr{
param($Country,$Source,$Template)

# (1) recup des infos dans control actuel // control source
if(! $TSName){$TSName = getcsvalue -Template "$Source\Control" -variable "TASKSEQUENCEID"}
if(! $UserID){$UserID = getcsvalue -Template "$Source\Control" -variable "UserID"}
if(! $UserDomain){$UserDomain = getcsvalue -Template "$Source\Control" -variable "UserDomain"}
if(! $MDTSRV){$MDTSRV = getcsvalue -Template "$Source\Control" -variable "MDTSRV="}
if(! $Country){$Country = getcsvalue -Template "$Source\Control" -variable "Country"}
if(! $LangCode){$LangCode = getcsvalue -Template "$Source\Control" -variable "UILanguage"}
if(! $KeyboardLocale){$KeyboardLocale = getcsvalue -Template "$Source\Control" -variable "KeyboardLocale"}
if(! $TimeZone){$TimeZone = getcsvalue -Template "$Source\Control" -variable "TimeZone="}
if(! $TimeZoneName){$TimeZoneName = getcsvalue -Template "$Source\Control" -variable "TimeZoneName"}
if(! $TargetMDT){$TargetMDT = $MDTSRV}
if(! $oldMDTSRV){$oldMDTSRV =getcsvalue -Template "$Template\control" -variable "MDTSRV="}
if(! $oldCountry){$oldCountry =getcsvalue -Template "$Template\control" -variable "Country"}
if(! $oldLangCode){$oldLangCode =getcsvalue -Template "$Template\control" -variable "UILanguage"}
if(! $oldKeyboardLocale){$oldKeyboardLocale =getcsvalue -Template "$Template\control" -variable "KeyboardLocale"}
if(! $oldTimeZone){$oldTimeZone =getcsvalue -Template "$Template\control" -variable "TimeZone="}
if(! $oldTimeZoneName){$oldTimeZoneName =getcsvalue -Template "$Template\control" -variable "TimeZoneName"}
if(! $oldUserDomain){$UserDomain =getcsvalue -Template "$Template\control" -variable "UserDomain"}


# (2) robocopy /E sourcectrl vers control_$country
cmd /c "robocopy /E $Template\Control $Source\Control"


# (3) perso avec les infos recup en (1)
    foreach($file in $Source){
        changevalue -file $file -old "%LangCode%" -new $Langcode
        if($oldCountry -ne $Country){
            changevalue -file $file -old $oldCountry -new $Country
            changevalue -file $file -old "COUNTRY=$oldCountry" -new "COUNTRY=$Country"
            }
        if($oldKeyboardLocale -ne $Keyboard){changevalue -file $file -old $oldKeyboardLocale -new $Keyboard}
        if($oldTimeZoneName -ne $TimeZoneName){
            changevalue -file $file -old $oldTimeZoneName -new $TimeZoneName
            changevalue -file $file -old "TimeZoneName=$oldTimeZoneName" -new "TimeZoneName=$TimeZoneName"
            }
        if($oldTimeZone -ne $TimeZone){
            changevalue -file $file -old $oldTimeZone -new $TimeZone
            changevalue -file $file -old "TimeZone=$oldTimeZone" -new "TimeZone=$TimeZone"
            }
        if($oldLangCode -ne $Langcode){changevalue -file $file -old $oldLangCode -new $Langcode}
        if($oldUserDomain -ne $UserDomain){changevalue -file $file -old $oldUserDomain -new $UserDomain}
        
        changevalue -file $file -old "=%LangCode%" -new "=$Langcode"
        changevalue -file $file -old "=%UILanguage%" -new "=$Langcode"
        changevalue -file $file -old "=%UserLocale%" -new "=$Langcode"
        changevalue -file $file -old "=%KeyboardLocale%" -new "=$Keyboard"
        changevalue -file $file -old "=%TimeZoneName%" -new "=$TimeZoneName"
        changevalue -file $file -old "MDTSRV=$oldMDTSRVdef" -new "MDTSRV=$TargetMDT"
        changevalue -file $file -old $oldMDTSRV -new $TargetMDT
        changevalue -file $file -old "MDTSRV=$oldMDTSRV" -new "MDTSRV=$TargetMDT"
        changevalue -file $file -old "$oldMDTSRVdef.$UserDomain" -new "$TargetMDT.$UserDomain"
        changevalue -file $file -old $oldMDTSRVdef -new $TargetMDT
            changevalue -file $file -old "$PrincipalMDTSRV.$UserDomain" -new "$TargetMDT.$UserDomain"
            changevalue -file $file -old $PrincipalMDTSRV -new $TargetMDT
            if($computername -notmatch $oldMDTSRVdef){changevalue -file $file -old "MDTSRV=$PrincipalMDTSRV" -new "MDTSRV=WINCHEHYP12"}
        changevalue -file $file -old "WSUSServer=http://$TargetMDT" -new "WSUSServer=http://$PrincipalMDTSRV"
        changevalue -file $file -old "EventService=http://$TargetMDT" -new "EventService=http://$PrincipalMDTSRV"

            if($Country -ne "France"){changevalue -file $file -old "WSUSServer=" -new "; WSUSServer="}
        changevalue -file $file -old "; ; " -new "; "
        changevalue -file $file -old "; ;" -new ";"
        changevalue -file $file -old ";; " -new ";"
    }

}

function AssignACls($fldr){
    param($fldr,$GRP)
    $ACLGRP = $GRP + ':'

logorhost("Apply ACLs to $fldr")
    cmd /c "icacls $fldr /grant $ACLGRP:(OI)(CI)(NP)(F) /T"
}

function CreateMediaIso{
param($Country,$Site,$SOURCEPATH,$ISOFILE)
    $chr = [char]34
    # $SOURCEPATH = $SOURCEPATH.replace(".iso","")
    # if(! $ISOFILE){$ISOFILE = $SOURCEPATH + '.iso'}
    
    # $ISOFILE = $ISOFILE.replace(".iso.iso",".iso") | out-null
    # if(! $SOURCEPATH){$SOURCEPATH = $ISOFILE.replace('.iso','')}
    $Cible = "$Country$Site"
    $LOGFILE = "$rootlogs\$Cible.LOG"
    $chroscdimg = $chr + $oscdimg + $chr
    $chretfsboot = $chr + $etfsboot + $chr
    $chrefisysbin = $chr + $efisysbin + $chr
    # write-host "ISOFILE = $ISOFILE"
    # write-host "LOGFILE = $LOGFILE"
    if($Build){
        cmd /c "del /F /Q $SOURCEPATH\Content\Deploy\Control\Drivers.xml"
        cmd /c "del /F /Q $SOURCEPATH\Content\Deploy\Control\DriverGroups.xml"
    }
    $cmdiso = "$chroscdimg -m -o -u2 -udfver102 -bootdata:2#p0,e,b$chretfsboot#pEF,e,b$chrefisysbin $SOURCEPATH\Content $ISOFILE >> $LOGFILE"

    if(test-path $ISOFILE){cmd /c "del /F /Q $ISOFILE 2>&1" | out-null}
    cls
    $Dest = split-path -parent $ISOFILE
    # write-host "Dest = $Dest"
    if(!(test-path $Dest)){cmd /c "md $Dest 2>&1" | out-null}
    if($Site){$Cible = "$Country\$Site"}else{$Cible = $Country}
    cls
    write-host "Create Boot Media $ISOFILE for $Cible"
    write-host $cmdiso
    write-host ""
    cmd /c $cmdiso
    
    # cmd /c "$oscdimg -m -o -u2 -udfver102 -bootdata:2#p0,e,b$etfsboot#pEF,e,b$efisysbin$SOURCEPATH\Content $ISOFILE >> $LOGFILE 2>&1"
return $ISOFILE
}

# function shareISO{
# param($ISOFILE,$FTPCountryPath)
    
# $ISOFILEFTP = $ISOFILE.replace($root,$FTPCountryPath)
# write-host "FTPCountryPath = $FTPCountryPath"
# write-host "ISOFILE = $ISOFILE"
# write-host "ISOFILEFTP = $ISOFILEFTP"

# if(test-path $ISOFILEFTP){cmd /c "del /F /Q $ISOFILEFTP 2>&1" | out-null}
# cmd /c "copy /Y $ISOFILE $ISOFILEFTP"
# logorhost("BootMedia for $Country Published")
# }

function PublishISO{
param($Country,$Site,$SOURCEPATH,$ISOFILE,$FTPCountryPath,[switch]$tst)
$FTPCountryPath = "$FTPPath\$Country"
$ISOFILE = $ISOFILE.replace(".iso.iso",".iso")
# $SOURCEPATH = $ISOFILE.replace(".iso","")
# $MEDIASOURCEPATH = $SOURCEPATH.replace(".iso","")
# [string]$SOURCEPATH = $MEDIASOURCEPATH.split(".")[0]

if($tst){
    cmd /c "explorer $SOURCEPATH"
    exit
}

logorhost("Create BootMedia $ISOFILE from $SOURCEPATH")

CreateMediaIso -Country $Country -Site $Site -SOURCEPATH $SOURCEPATH -ISOFILE $ISOFILE
sleep 5
logorhost("BootMedia for $Country Published")
# logorhost("Publish BootMedia $ISOFILE to $Country FTP:")
# $ISOFILE = $ISOFILE.replace('.iso.iso','.iso') | out-null
# shareISO -ISOFILE $ISOFILE -FTPCountryPath "$FTPCountryPath\$Country"
}

function copycontrolsFile($MDTPath, $TargetMDTDrive){
logorhost("Distrib $Country Control to by order: $TargetMDTDrive")
$order = " DriverGroups.xml"
$order = "$order`n ApplicationGroups.xml"
$order = "$order`n OperatingSystemGroups.xml"
$order = "$order`n TaskSequenceGroups.xml"
$order = "$order`n PackageGroups.xml"
$order = "$order`n SelectionProfileGroups.xml"
$order = "$order`n MediaGroups.xml"
$order = "$order`n LinkedDeploymentShareGroups.xml"
$order = "$order`n Drivers.xml"
$order = "$order`n Applications.xml"
$order = "$order`n OperatingSystems.xml"
$order = "$order`n TaskSequences.xml"
$order = "$order`n Packages.xml"
$order = "$order`n SelectionProfiles.xml"
$order = "$order`n Medias.xml"
$order = "$order`n LinkedDeploymentShares.xml"
$order = "$order`n Settings.xml"
$order = "$order`n Version.xml"
$order = "$order`n MedCustomSettings.ini"
$order = "$order`n CustomSettings.ini"
$order = "$order`n Bootstrap.ini"

logorhost("Copy $MDTPath\control to $TargetMDTDrive\control in predefine order:")
logorhost $order

cmd /c "copy /Y $MDTPath\control\DriverGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\ApplicationGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\OperatingSystemGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\TaskSequenceGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\PackageGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\SelectionProfileGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\MediaGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\LinkedDeploymentShareGroups.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Drivers.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Applications.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\OperatingSystems.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\TaskSequences.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Packages.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\SelectionProfiles.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Medias.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\LinkedDeploymentShares.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Settings.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Version.xml $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\MedCustomSettings.ini $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\CustomSettings.ini $TargetMDTDrive\Control"
cmd /c "copy /Y $MDTPath\control\Bootstrap.ini $TargetMDTDrive\Control"    
}

function genNupdtMDTSources{
    param([switch]$tst)
    # write-host "fct: genNupdtMDTSources"
    # pause
    # function genNupdtMDTSources([switch]$CTRL){
    # $result = $false

    foreach($LPInfosCSV in $LPInfosCSVs){
        $Pays = $LPInfosCSV.Pays
        $Site = $LPInfosCSV.Site
        if(! $Site){$Site=""}
        $syncMDT = $LPInfosCSV.syncMDT
        
        if($syncMDT -eq "YES"){
            
            $MDTSRV = $LPInfosCSV.MDTSRV
            if((! $MDTSRV) -or ($MDTSRV -eq "")){$MDTSRV = "USBKEY"}
            
            logorhost("ReBuild MDT for $Pays$Site")
            if($MDTSRV -eq "USBKEY"){$MDTCountry = "$rootMDTCountry\Media_$Pays$Site\Content\Deploy"}else{$MDTCountry = "$rootMDTCountry\MDT_$Pays$Site"}
            $CTRLCountry = "$MDTCountry\Control"

            if($tst){createctrlcountry -Country $Pays -MDTSRV $MDTSRV -Site $Site -tst}else{createctrlcountry -Country $Pays -MDTSRV $MDTSRV -Site $Site}
            
            logorhost("Build TemplateMDT MDTCountry for $Pays-$Site if necessary")
                
            if(!(test-path $MDTCountry)){cmd /c "md $MDTCountry"}
            if($MDTSRV -eq "USBKEY"){
                cmd /c "robocopy /E $rootBootMedia\Content $rootMDTCountry\Media_$Pays$Site\Content"
                # $MDTCountry = "$MDTCountry\Content\Deploy"
            }
            if(!(test-path "$MDTCountry\Backup")){cmd /c "md $MDTCountry\Backup"}
            if(!(test-path "$MDTCountry\Captures")){cmd /c "md $MDTCountry\Captures"}
            if(!(test-path "$MDTCountry\logs")){cmd /c "md $MDTCountry\logs"}
            if(!(test-path "$MDTCountry\scripts")){cmd /c "md $MDTCountry\scripts"}
                cmd /c "ROBOCOPY /E $DSCentral\scripts $MDTCountry\scripts /XD $ContractorClient"
                cmd /c "MKLINK /D /H /J $MDTCountry\scripts\$ContractorClient $DSCentral\scripts\$ContractorClient"
                    if($MDTSRV -eq "USBKEY"){cmd /c "copy /Y $MDTCountry\Scripts\MedLiteTouch.wsf $MDTCountry\Scripts\LiteTouch.wsf"}

            $DSCentralboot = "$DSCentral\boot"
            $MDTCountryboot = "$MDTCountry\boot"
            if(!(test-path $MDTCountryboot)){
                cmd /c "md $$MDTCountryboot 2>&1" | out-null
                cmd /c "ROBOCOPY /E $DSCentralboot $MDTCountryboot"
            }
            $bootwimDSCentral = "$DSCentralboot\LiteTouchPE_x64.wim"
            $bootwimMDTCountry = "$MDTCountryboot\LiteTouchPE_x64.wim"
            $bootwimDSCentralLastWriteTime = (get-item $bootwimDSCentral).LastWriteTime.Date
            $bootwimMDTCountryLastWriteTime = (get-item $bootwimMDTCountry).LastWriteTime.Date
            if(! $tst){if($bootwimDSCentralLastWriteTime -ne $bootwimMDTCountryLastWriteTime){cmd /c "ROBOCOPY /E $DSCentralboot $MDTCountryboot"}}
            
            $MDTCountryOEM = $MDTCountry + '\$OEM$'
            $DSCentralOEM = $DSCentral + '\$OEM$'
            $MDTCountryOS = $chr + "$MDTCountry\Operating Systems" + $chr
            $DSCentralOS = $chr + "$DSCentral\Operating Systems" + $chr
            $MDTCountryOoBD = $chr + "$MDTCountry\Out-of-Box Drivers" + $chr
            $DSCentralOoBD = $chr + "$DSCentral\Out-of-Box Drivers" + $chr
            cmd /c "MKLINK /D /H /J $MDTCountryOEM $DSCentralOEM"
            cmd /c "MKLINK /D /H /J $MDTCountryOS $DSCentralOS"
            logorhost("MKLINK $MDTCountryOoBD <<===>> $DSCentralOoBD")
            cmd /c "MKLINK /D /H /J $MDTCountryOoBD $DSCentralOoBD 2>&1" | out-null
            $JunctFldrs = @('Applications','Packages','Servicing','Templates','Tools')
            foreach($JunctFldr in $JunctFldrs){if(!(test-path "$MDTCountry\$JunctFldr")){cmd /c "MKLINK /D /H /J $MDTCountry\$JunctFldr $DSCentral\$JunctFldr"}}

            cmd /c "copy /Y $DSCentral\sync.txt $MDTCountry"
            cmd /c "copy /Y $DSCentral\UpdBootMedia.ps1 $MDTCountry"
            "" | out-file "$MDTCountry\Audit.log" -Encoding ascii -Force
            }

            # if(test-path "$MDTCountry\control"){cmd /c "rmdir /S /Q $MDTCountry\control"}
            # if($Prod){AssignACls($CTRLCountry)}
            # cmd /c "MKLINK /D /H /J $MDTCountry\control $CTRLCountry"
            }

    
# $result = $true
# return $result
}

function watch{
param ([string]$location)
$includeSubdirectories = $true
$includeChanged = $true
$includeRenamed = $true
$includeCreated = $true
$includeDeleted = $true
           
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = $location
    $watcher.IncludeSubdirectories = $includeSubdirectories
    $watcher.EnableRaisingEvents = $false
    $watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite -bor [System.IO.NotifyFilters]::FileName
    
    $conditions = 0
    if($includeChanged){
        $conditions = [System.IO.WatcherChangeTypes]::Changed 
    }

    if($includeRenamed){
        $conditions = $conditions -bOr [System.IO.WatcherChangeTypes]::Renamed
    }

    if($includeCreated){
        $conditions = $conditions -bOr [System.IO.WatcherChangeTypes]::Created 
    }

    if($includeDeleted){
        $conditions = $conditions -bOr [System.IO.WatcherChangeTypes]::Deleted
    }
    
    while($TRUE){
        $result = $watcher.WaitForChanged($conditions, 10000);
        if($result.TimedOut){
            continue;
        }
        $filepath = [System.IO.Path]::Combine($location, $result.Name)
        New-Object Object |
          Add-Member NoteProperty Path $filepath -passThru | 
          Add-Member NoteProperty Operation $result.ChangeType.ToString() -passThru | 
          write-output
    }
}

function TimeRunSyncCible{
param($Country)
[int]$baseTimeCible = $LPInfosCSVs | foreach{if($_.Pays -match $Country){$_.UTC}}
$endtimejob = "21:00:00"
$finwatch = [TimeSpan]::Parse($endtimejob)
$dbtsync = ($finwatch.Add([TimeSpan]::FromMinutes(5)))
[int]$baseTimeFrance = +1
$UTC = ($dbtsync.Add([TimeSpan]::FromHours(- $baseTimeFrance)))
$SyncTimeCible = ($UTC.Add([TimeSpan]::FromHours(- $baseTimeCible)))
[string]$res = $SyncTimeCible.ToString()
[int]$Hours = $SyncTimeCible.Hours
[int]$endHoursjob = $endtimejob.substring(0,2)
if(($Hours -ge 8) -and ($Hours -le 21)){$res = "21:30:00"}
return $res
}

function CreateSchedDay{
#créer un schedule [at $FranceHNO+Diff(UTC)] par pays nommé HNODistrib<nom du pays> qui lancera HNODistribution.ps1 -source <nom du pays>

    #######################################################################
    logorhost("Create Schedule to Check if there is a sync to do Day By Day")

    # lié au script de maj (HNODistribution.ps1 -source $Country):

                $ScriptSurvey = "$scriptpath\SyncClones.ps1"
                $TaskName = "ChkIfSyncToDo"
                $xmlTaskName = "$TaskName.xml"
                $xmlTaskPath = "$scriptpath\$xmlTaskName"
                $StartTime = $starttimejob
                
                # Create the scheduled task
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%SRV%",$computername} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%TaskName%",$TaskName} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%StartTime%",$StartTime} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%Enabled%","true"} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%Arguments%","-file $ScriptSurvey"} | Set-Content $xmlTaskPath
                schtasks /create /xml $xmlTaskPath /tn "\$TaskName" /ru System

}

function createSynchro{
    param($Country,$Site)
#créer un schedule [at $FranceHNO+Diff(UTC)] par pays nommé HNODistrib<nom du pays> qui lancera HNODistribution.ps1 -source <nom du pays>

    #######################################################################
    logorhost("Create HNO Distribution for MDTCountry to: $Pays")

    # lié au script de maj (HNODistribution.ps1 -source $Country):

        $LPInfosCSVs | foreach{
            if($_.Pays -match $Country){
                if(($_.syncMDT -eq "YES") -and ($_.MDTSRV -ne "USBKEY")){
            $MDTCountry = "$rootMDTCountry\MDT_$Country"
                if(test-path $MDTCountry){
                if(!(test-path "$scriptpath\HNODISTRIB$Country.xml")){
                # cmd /c "del /F /Q $scriptpath\HNODISTRIB$Country.xml 2>&1" | out-null
                cmd /c "copy /Y $scriptpath\SCHEDULEHNODISTRIB.xml $scriptpath\HNODISTRIB$Country.xml"

                $ScriptSurvey = "$scriptpath\HNODistribution.ps1 -source $Country"
                $TaskName = "HNODistrib$Country"
                $xmlTaskName = "$TaskName.xml"
                $xmlTaskPath = "$scriptpath\$xmlTaskName"
                $StartTime = TimeRunSyncCible -Country $Country
                        

                # Create the scheduled task
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%SRV%",$computername} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%TaskName%",$TaskName} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%StartTime%",$StartTime} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%Enabled%","false"} | Set-Content $xmlTaskPath
                (Get-Content $xmlTaskPath) | ForEach {$_ -replace "%Arguments%","-file $ScriptSurvey"} | Set-Content $xmlTaskPath
                schtasks /create /xml $xmlTaskPath /tn "\$TaskName" /ru System

                }}
                }
            }
    }
return $TaskName
}

function ChkModif($fldr){
[int]$result = 0
$vals = (Get-ChildItem -Path "$DSCentral\$fldr" -recurse)
$vals | foreach{
    $file = Get-ItemProperty -Path $_.FullName
    $LastWrite = $file.LastWriteTime.Date
    $Creation = $file.CreationTime.Date
    $DateTag = $LastWrite
    if($LastWrite -lt $Creation){$DateTag = $Creation}
    if($DateTag -eq $today){$result = 1}
    }
return $result
}

function istosync{
$res = $false
[int]$Applications = ChkModif("Applications")
[int]$Scripts = ChkModif("Scripts")
[int]$Control = ChkModif("Control")
    if(($Applications + $Control + $Scripts) -ne 0){$res = $true}
return $res
}

function SurveyToSync{
$syncdrv="no"
$Controlfiles = (Get-ChildItem -Path "$DSCentral\Control" -recurse)
foreach($Controlfile in $Controlfiles | where-object{(($_.Name -match "Driver") -and ($_.Name -match ".xml"))}){
    $LastWrite = (Get-ItemProperty -Path $Controlfile.FullName).LastWriteTime.Date
    if($LastWrite -eq $today){$syncdrv = "yes"}
}
if(istosync){"drv=$syncdrv,$Stringtoday" | out-file $SyncTagFile -Encoding ascii -Force}
}

function IsToSyncMDT($SyncTagFile){
$synccopy = $false
$OoBD = $chr + 'Out-of-Box Drivers' + $chr
    get-content -path $SyncTagFile | foreach{
        $drv = ($_.split("=")[1]).split(",")[0]
        $lastdate = $_.split(",")[1]
        # write-host "drv=$drv / lastdate=$lastdate / today=$Stringtoday"
        if($drv -eq "yes"){$Global:exclude = " /XD $OoBD"}else{$Global:exclude = ""}
        if($lastdate -match $Stringtoday){$synccopy = $true}
    }
    
return $synccopy
}

function updtFromMDTCountriesSrc{
    $cmds = "echo updt MDT Countries" | out-file "$scriptpath\updtFromMDTCountriesSrc.cmd" -Encoding ascii -Force
$LPInfosCSVs | foreach{
    $MDTSRV = $_.MDTSRV
    $syncMDT = $_.syncMDT
    $Country = $_.Pays

    if(($MDTSRV -ne "USBKEY") -and ($syncMDT -eq "YES")){
        write-host "MDTSRV = $MDTSRV"
        $Target = '\\' + $MDTSRV + '\MDTProduction$'
        $TargtDrive = "U:"
        "net use $TargtDrive $Target" | out-file "$scriptpath\updtFromMDTCountriesSrc.cmd" -Append -Encoding ascii -Force
        "robocopy /E $rootMDTCountry\MDT_$Country $TargtDrive\$exclude /LOG+:$rootlogs\Sync$Country$Stringtoday.log" | out-file "$scriptpath\updtFromMDTCountriesSrc.cmd" -Append -Encoding ascii -Force
        "net use $TargtDrive /d /y" | out-file "$scriptpath\updtFromMDTCountriesSrc.cmd" -Append -Encoding ascii -Force
    }
}

}

function getTSvalue{
    param($VAR)
    if($tsenv){
        $Value = $tsenv.Value($VAR)
        if(! $Value){
        if($TSEnvironments){foreach($TSEnvironment in $TSEnvironments){if($TSEnvironment.Name -eq $VAR){$Value = $TSEnvironment.Value}}}
            if(! $Value){if($TSEnvironmentList){foreach($TSEnvironment in $TSEnvironmentList){if($TSEnvironment.Name -eq $VAR){$Value = $TSEnvironment.Value}}}}
        }
    }
    # else{$Value = getlocalanswers($var)}
return $Value
}

#Variables
$dollar = [char]36
$chr = [char]34
$etoile = [char]42

if(test-path "C:\Windows"){$OSDisk = "C:"; $temp = $env:temp; $ALLUSERSPROFILE = $env:PUBLIC}else{$OSDisk = getTSvalue -VAR "OSDisk"}
    
if(! $tsenv){
$DEPLOYROOT = "Z:"
$DEPLOYDRIVE = $DEPLOYROOT
$TSTMDT = "YES"
$OSDCOMPUTERNAME = $env:computername
$MACADDRESS = (get-netadapter | where-object {$_.Status -ne "Disconnected"}).MacAddress
$logpath = "$temp\logs_$OSDCOMPUTERNAME"
$ThisRegion = "France"
$PHASE = "OutOfMDT"
}else{
$AdminPassword = getTSvalue -VAR "AdminPassword"
$DEPLOYROOT = getTSvalue -VAR "DEPLOYROOT"
$DEPLOYDRIVE = getTSvalue -VAR "DEPLOYDRIVE"
$TSTMDT = getTSvalue -VAR "TSTMDT"
$OSDCOMPUTERNAME = getTSvalue -VAR "OSDCOMPUTERNAME"
$ThisRegion = getTSvalue -VAR "ThisRegion"
$Domain = getTSvalue -VAR "UserDomain"
$UserDomain = $Domain
$UserID = getTSvalue -VAR "UserID"
$UserPassword = getTSvalue -VAR "UserPassword"
$logpath = getTSvalue -VAR "logpath"
$PHASE = getTSvalue -VAR "PHASE"
$SMSTSCurrentActionName = getTSvalue -VAR "_SMSTSCurrentActionName"
$MACADDRESS = getTSvalue -VAR "MACADDRESS"
}


$SCRIPTSROOT = "$DEPLOYROOT\scripts"
$logfilename = $script.replace(".ps1",".log")
$LogFileFullName = "$logpath\$logfilename"
Import-Module "$SCRIPTSROOT\ZTIUtility.psm1"

function addregDWORD{
    param($regkey,$value,$data)
    write-host "assign $regkey!$value(REG_DWORD)=$data"
    REG ADD "HKLM\DEFAULT\$regkey" /v $value /T REG_DWORD /D $data /F
    REG ADD "HKCU\$regkey" /v $value /T REG_DWORD /D $data /F
}

function addregSZ{
    param($regkey,$value,$data)
    REG ADD "HKLM\DEFAULT\$regkey" /v $value /T REG_SZ /D $data /F
    REG ADD "HKCU\$regkey" /v $value /T REG_SZ /D $data /F
}

function delreg{
param($regkey,$value)
    if($value){
    $Path = "HKLM:\DEFAULT\$regkey"
    if(Get-ItemProperty -Path $Path | Select-Object -ExpandProperty $value){REG DELETE $Path.replace(":\","\") /v $value /f | out-null}
    $Path = "HKCU:\$regkey"
    if(Get-ItemProperty -Path $Path | Select-Object -ExpandProperty $value){REG DELETE $Path.replace(":\","\") /v $value /f | out-null}
    }else{
    $Path = "HKLM:\DEFAULT\$regkey"
    if(Get-ItemProperty -Path $Path){REG DELETE $Path.replace(":\","\") /f | out-null}
    $Path = "HKCU:\$regkey"
    if(Get-ItemProperty -Path $Path){REG DELETE $Path.replace(":\","\") /f | out-null}
    }
}

function CopyItem{
    param($trgt,$dest,[switch]$Recurse)
    if(test-path $trgt){
        write-host "Copy-Item $trgt -Destination $dest"
        if($Recurse){Copy-Item $trgt -Destination $dest -force -Recurse}else{Copy-Item $trgt -Destination $dest -force}
        }
}

function delobjectlocalAPPDATA($obj){
    $userAPPDATAs = @($PublicLocalAppdata,$AdminLocalAppdata,$DefLocalAppdata)
    foreach($userAPPDATA in $userAPPDATAs){
    if(test-path "$userAPPDATA\$obj"){cmd /c "del /f /q " + $chr + "$userAPPDATA\$obj" + $chr + " > null"}
    }
}


function delobjectAPPDATA($obj){
    $userAPPDATAs = @($PublicAPPDATA,$AdminAPPDATA,$DefAPPDATA)
    foreach($userAPPDATA in $userAPPDATAs){
    if(test-path "$userAPPDATA\$obj"){cmd /c "del /f /q " + $chr + "$userAPPDATA\$obj" + $chr + " > null"}
    }
}


function delobjectlocal($obj){
    $userAPPDATAs = @($localPublic,$localAdministrator,$localDefault)
    foreach($userAPPDATA in $userAPPDATAs){
    if(test-path "$userAPPDATA\$obj"){cmd /c "del /f /q " + $chr + "$userAPPDATA\$obj" + $chr + " > null"}
    }
}

function regeditsilent{
    param($val)
    if(test-path $val){
        write-host "regedit /s $val"
        regedit /s $val
        }else{
        write-host "$val not exist"
        }            
}

Commenter cet article