Compare commits

...

36 Commits

Author SHA1 Message Date
0ca69930fa Script sauvegarde aubrac sur dracnew 2023-01-18 11:58:57 +01:00
dda78c5161 Ajout clef publique foret labastide 2021-11-06 10:02:18 +01:00
d55d8ce9f0 ajout script backup enjalbert 2021-05-19 18:09:20 +02:00
f51eb64e2f ajout script robocpy-backup.ps1 2021-01-21 16:38:14 +01:00
f509db8adf Sortie de get start apps 2020-02-13 16:59:51 +01:00
8b41a74918 Script nettoyage WSUS updates 2020-02-07 16:31:05 +01:00
e6fa14ecd0 Synchro GLPI ordis vers itop PC
en utilisant des modules powershell pour accéder au API GLPI et Itop + un peu de php
2020-01-17 15:24:26 +01:00
c91332ccac SCCM/commande_install_client_sccm 2019-01-16 09:46:58 +01:00
841dd6e72d ajout commande pour enter PSSession 2018-09-20 09:31:57 +02:00
f459157f62 Ajout clef de registres pour image win10 1803
Désactive le windws store update lors du sysprep
2018-06-14 15:30:06 +02:00
b92bf4f344 Ajout script installation image administrative de solidworks 2018-05-25 16:27:12 +02:00
59cbb66d86 Fichier Unattended de base pour copier le profile par défaut lors du sysprerp 2018-05-15 13:50:29 +02:00
ab7a961f3c Liste d'appx à supprimmer 2018-05-15 13:48:41 +02:00
e7ab0b7d1b Script pour supprimer les Appx en live 2018-05-15 13:47:54 +02:00
8293d9b34a Fichier qui fonctionne sur un windows 10 1709 2018-04-27 16:16:57 +02:00
908e8d5592 modification balises pour win10 1709 2018-04-26 15:32:38 +02:00
d201985e44 Modifications pour tests 2018-04-26 15:24:21 +02:00
c83074d0c4 Essai modif pour AppuUerModelID au lieu des DesktopApplicationLinkPath 2018-04-25 11:47:03 +02:00
a8fb306984 ajout de la customization de la barre des taches 2018-04-25 11:07:46 +02:00
d59411c64c Ajout du fichier de parametrage menu démarer windows 10 salle a 203 2018-04-25 11:04:46 +02:00
3fdc9468db ajout netfx3 sur image win10 1709 2018-04-09 15:41:56 +02:00
160e0dd563 Correction variables +ajout commentaire 2018-04-09 11:43:41 +02:00
fe0a982699 fichier pour profil powershell et enregistrer history 2018-04-09 11:07:58 +02:00
cb7b38c612 ajout commandes sur hyper2 2018-04-09 11:00:39 +02:00
ec37433935 ajout commandes pour role hyperV
Ajout des commandes faites pour le role hyper V +mise en place réplication via certificats
2018-04-09 10:50:08 +02:00
423f80eb96 Ajout et modif scripts pour modifier image windows 10 viapowershell et la source install.wim 2018-02-21 09:05:16 +01:00
566b6b5217 Trouver le Application User Model ID d'une application installée 2018-02-20 15:21:09 +01:00
3157f1dffd ajout historique commande pour removeapps sur un windows 7 2018-02-14 16:48:11 +01:00
17d8bc5e11 Ajout script technet pour créer une arborescence de collections sous sccm 2018-02-14 14:32:10 +01:00
01e78a7c61 Ajout d'un script Technet pour regénerer les images de boot sur SCCM
Pour régénérer les images de boot sur SCCM après une MAJ du Windows Deployment Kit
Sur SCCM :
Désinstall du windows deployment kit
Installation de la nouvelle version ADKSetup
Reboot du serveur
Passage du script
Possible reboot du serveur
2018-02-08 15:14:19 +01:00
fa2a06a5fa Modif commande recherche de fichier 2018-02-07 14:08:10 +01:00
1efe577cf0 Ajout d'exemples de commandes powershell pour serveur core 2016 2018-02-07 13:43:38 +01:00
cb54c22514 Ajout de scripts pour récupérer les infos sur les groupes de l'AD 2018-02-06 09:35:00 +01:00
d0cd6bfb28 Ajout script de backup windows via robocopy 2018-02-02 23:11:12 +01:00
4aa8f16d95 Merge branch 'master' of https://git.iut-rodez.fr/andre/Powershell_Scripts 2018-02-02 14:57:46 +01:00
ebb45769f5 Ajout script activationKMS Windows et office all versions 7 et 10 2013 2016 2018-02-02 14:57:07 +01:00
34 changed files with 3929 additions and 3 deletions

BIN
Compare-ADGroup.ps1 Normal file

Binary file not shown.

61
Get-ADUserGroup.ps1 Normal file
View File

@@ -0,0 +1,61 @@
<#
.SYNOPSIS
This function returns the list of the groups a user inherits from his token
.DESCRIPTION
This function searches the SIDs of groups inherited from a user and translates them into Ldap names based on the global catalog. The function works on a multi-domain forest
.PARAMETER user
The SamAccountName from user
.PARAMETER DomainController
A domain controller of the user domain that will execute the command.
The domain controller must be a global catalog.
If it is not set the function, will determine a domain controller.
.EXAMPLE
Get-ADUserGroup -user pbarth -DomainController 2016dc1.htrab.lan
GroupDN Nom
------- ---
CN=Utilisateurs,CN=Builtin,DC=htrab,DC=lan Utilisateurs
CN=SDL-CT-Partage-Info,OU=Securite_Domaine,OU=Groupes,DC=htrab,DC=lan SDL-CT-Partage-Info
CN=SDL-R-Partage-Compta,OU=Securite_Domaine,OU=Groupes,DC=htrab,DC=lan SDL-R-Partage-Compta
CN=SDL-M-Imprimante-Direction,OU=Securite_Domaine,OU=Groupes,DC=htrab,DC=lan SDL-M-Imprimante-Dire...
CN=Utilisateurs du domaine,CN=Users,DC=htrab,DC=lan Utilisateurs du domaine
CN=SG-Service-Informatique,OU=Securite_global,OU=Groupes,DC=htrab,DC=lan SG-Service-Informatique
.NOTES
Author: Philippe BARTH
Version: 1.0
#>
# Déclaration des paramètres
param([string]$user, [string]$DomainController = (Get-ADDomainController -Discover -Service GlobalCatalog).hostname)
#
#gestion des erreurs
Trap
{
#continue
}
#Fonction
$userdn =(Get-ADUser $user -Server $DomainController).DistinguishedName
$liste_groupes = Get-ADUser -SearchScope Base -SearchBase $userdn -LDAPFilter '(objectClass=user)' -Properties tokenGroups -server $DomainController| Select-Object -ExpandProperty tokenGroups | Select-Object -ExpandProperty Value
$liste=@()
foreach ($g in $liste_groupes)
{
$GC=$DomainController+":3268"
$b= Get-ADGroup -filter { Sid -eq $g } -server $GC
$r= New-Object -TypeName PSObject -Property @{
Name = $b.Name
DN = $b.DistinguishedName
}
$liste += $r
}
return $liste

2
PSSession.ps1 Normal file
View File

@@ -0,0 +1,2 @@
PS C:\Users\administrateur.IUT> $sessi = New-PSSession -ComputerName a201a3,a201a4,a201a5,a201a6,a201a7,a201a8,a201b1,a201b2,a201b3,a201b4,a201b5,a201b6,a201b7,a201b8,a201c1,a201c2,a201c3,a201c4,a201c5,a20
1c6,a201c7,a201c8 -Credential administrateur@iut.local

View File

@@ -0,0 +1,307 @@
#############################################################################
# Author : Jonathan Lefebvre-Globensky
# Website : www.SystemCenterDudes.com
# Twitter : @jlefebvregloben, @SCDudes
#
# Version : 1.0
# Created : 2018/01/15
# Modified :
#
# Purpose : This script create a structure of folders to classify collections based on the purpose and define a naming convention. BAsic collections are also created at the same time
# Blog post related : https://www.systemcenterdudes.com/powershell-script-create-set-maintenance-collections
# Want more default operationnal collection? See Benoit Lecours powershell script --> https://gallery.technet.microsoft.com/Set-of-Operational-SCCM-19fa8178
#
#############################################################################
#Load Configuration Manager PowerShell Module
Import-module ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1')
#Get SiteCode
$SiteCode = Get-PSDrive -PSProvider CMSITE
Set-location $SiteCode":"
#Create Defaut Folders
new-item -NAme 'Master Collections' -Path $($SiteCode.Name+":\DeviceCollection")
new-item -NAme 'MC - Client Settings' -Path $($SiteCode.name+":\DeviceCollection\Master Collections")
new-item -NAme 'MC - Endpoint Protection' -Path $($SiteCode.name+":\DeviceCollection\Master Collections")
new-item -NAme 'Workstations' -Path $($SiteCode.name+":\DeviceCollection")
new-item -NAme 'WKS - Inventory' -Path $($SiteCode.name+":\DeviceCollection\Workstations")
new-item -NAme 'WKS - Operating System' -Path $($SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory")
new-item -NAme 'WKS - Software' -Path $($SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory")
new-item -NAme 'WKS - Hardware' -Path $($SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory")
new-item -NAme 'WKS - Software Update' -Path $($SiteCode.name+":\DeviceCollection\Workstations")
new-item -NAme 'WKS - Software Distribution' -Path $($SiteCode.name+":\DeviceCollection\Workstations")
new-item -NAme 'WKS - OS deployment' -Path $($SiteCode.name+":\DeviceCollection\Workstations")
new-item -NAme 'Servers' -Path $($SiteCode.name+":\DeviceCollection")
new-item -NAme 'SRV - Inventory' -Path $($SiteCode.name+":\DeviceCollection\Servers")
new-item -NAme 'SRV - Operating System' -Path $($SiteCode.name+":\DeviceCollection\Servers\SRV - Inventory")
new-item -NAme 'SRV - Software' -Path $($SiteCode.name+":\DeviceCollection\Servers\SRV - Inventory")
new-item -NAme 'SRV - Hardware' -Path $($SiteCode.name+":\DeviceCollection\Servers\SRV - Inventory")
new-item -NAme 'SRV - Software Update' -Path $($SiteCode.name+":\DeviceCollection\Servers")
new-item -NAme 'SRV - Software Distribution' -Path $($SiteCode.name+":\DeviceCollection\Servers")
#Create Collections
#List of Collections Query
$Collection1 = @{Name = "All Servers"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where OperatingSystemNameandVersion like '%Server%'"}
$Collection2 = @{Name = "All Workstations"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation%'"}
$Collection3 = @{Name = "All Workstations - Admin"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation%'"}
$Collection4 = @{Name = "MC - CS - Workstation Prod"; Query = ""}
$Collection5 = @{Name = "MC - CS - Workstation Test"; Query = ""}
$Collection6 = @{Name = "MC - CS - Server Prod"; Query = ""}
$Collection7 = @{Name = "MC - CS - Server Test"; Query = ""}
$Collection8 = @{Name = "MC - EP - Workstation Prod"; Query = ""}
$Collection9 = @{Name = "MC - EP - Workstation Test"; Query = ""}
$Collection10 = @{Name = "MC - EP - Server Prod"; Query = ""}
$Collection11 = @{Name = "MC - EP - Server Test"; Query = ""}
$Collection12 = @{Name = "SRV - INV - Physical"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.ResourceId not in (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_R_System.IsVirtualMachine = 'True') and SMS_R_System.OperatingSystemNameandVersion like 'Microsoft Windows NT%Server%'"}
$Collection13 = @{Name = "SRV - INV - Virtual"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.IsVirtualMachine = 'True' and SMS_R_System.OperatingSystemNameandVersion like 'Microsoft Windows NT%Server%'"}
$Collection14 = @{Name = "SRV - INV - Windows 2008 and 2008 R2"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Server 6.0%' or OperatingSystemNameandVersion like '%Server 6.1%'"}
$Collection15 = @{Name = "SRV - INV - Windows 2012 and 2012 R2"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Server 6.2%' or OperatingSystemNameandVersion like '%Server 6.3%'"}
$Collection16 = @{Name = "SRV - INV - Windows 2003 and 2003 R2"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Server 5.2%'"}
$Collection17 = @{Name = "SRV - INV - Windows 2016"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Server 10%'"}
$Collection18 = @{Name = "WKS - INV - Windows 7"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation 6.1%'"}
$Collection19 = @{Name = "WKS - INV - Windows 8"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation 6.2%'"}
$Collection20 = @{Name = "WKS - INV - Windows 8.1"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation 6.3%'"}
$Collection21 = @{Name = "WKS - INV - Windows XP"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation 5.1%' or OperatingSystemNameandVersion like '%Workstation 5.2%'"}
$Collection22 = @{Name = "WKS - INV - SCCM Console"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName like '%Configuration Manager Console%'"}
$Collection23 = @{Name = "WKS - INV - Clients Version | 1710"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.ClientVersion like '5.00.8577.100%'"}
$Collection24 = @{Name = "WKS - INV - Laptops | Dell"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_G_System_COMPUTER_SYSTEM.Manufacturer like '%Dell%'"}
$Collection25 = @{Name = "WKS - INV - Laptops | Lenovo"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_G_System_COMPUTER_SYSTEM.Manufacturer like '%Lenovo%'"}
$Collection26 = @{Name = "WKS - INV - Laptops | HP"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_G_System_COMPUTER_SYSTEM.Manufacturer like '%HP%' or SMS_G_System_COMPUTER_SYSTEM.Manufacturer like '%Hewlett-Packard%'"}
$Collection27 = @{Name = "WKS - INV - Microsoft Surface 4"; Query = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_G_System_COMPUTER_SYSTEM.Model = 'Surface Pro 4'"}
$Collection28 = @{Name = "WKS - INV - Windows 10"; Query = "select SMS_R_System.ResourceID,SMS_R_System.ResourceType,SMS_R_System.Name,SMS_R_System.SMSUniqueIdentifier,SMS_R_System.ResourceDomainORWorkgroup,SMS_R_System.Client from SMS_R_System where OperatingSystemNameandVersion like '%Workstation 10.%'"}
$Collection29 = @{Name = "WKS - OSD - Windows 10 - PROD";Query=""}
$Collection30 = @{Name = "WKS - OSD - Windows 10 - TEST";Query=""}
$Collection31 = @{Name = "WKS - SU - Exclusion";Query=""}
$Collection32 = @{Name = "WKS - SU - Pilote";Query=""}
$Collection33 = @{Name = "WKS - SU - TEST";Query=""}
$Collection34 = @{Name = "WKS - SU - PROD";Query=""}
$Collection35 = @{Name = "WKS - SD - Office 365 - PROD";Query=""}
$Collection36 = @{Name = "WKS - SD - Office 365 - TEST";Query=""}
#Define possible limiting collections
$LimitingCollectionAll = "All Systems"
$LimitingCollectionAllWork = "All Workstations"
$LimitingCollectionAllWorkAdmin = "All Workstations - Admin"
$LimitingCollectionAllServer = "All Servers"
#Refresh Schedule
$Schedule = New-CMSchedule RecurInterval Days RecurCount 7
#Create Collection
#try{
New-CMDeviceCollection -Name $Collection1.Name -Comment "All Servers" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection1.Name -QueryExpression $Collection1.Query -RuleName $Collection1.Name
Write-host *** Collection $Collection1.Name created ***
New-CMDeviceCollection -Name $Collection2.Name -Comment "All Workstations" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection2.Name -QueryExpression $Collection2.Query -RuleName $Collection2.Name
Write-host *** Collection $Collection2.Name created ***
New-CMDeviceCollection -Name $Collection3.Name -Comment "All workstations admin, to hide from technician" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection3.Name -QueryExpression $Collection3.Query -RuleName $Collection3.Name
Write-host *** Collection $Collection3.Name created ***
New-CMDeviceCollection -Name $Collection4.Name -Comment "Prod client settings for workstations" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionIncludeMembershipRule -Name $Collection4.Name -IncludeCollectionName $collection2.name
Write-host *** Collection $Collection4.Name created ***
New-CMDeviceCollection -Name $Collection5.Name -Comment "Test client settings for workstations" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection5.Name created ***
New-CMDeviceCollection -Name $Collection6.Name -Comment "Prod client settings for servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionIncludeMembershipRule -Name $Collection6.Name -IncludeCollectionName $collection1.name
Write-host *** Collection $Collection6.Name created ***
New-CMDeviceCollection -Name $Collection7.Name -Comment "Test client settings for servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection7.Name created ***
New-CMDeviceCollection -Name $Collection8.Name -Comment "Endpoint Protection Policy for Prod Workstations" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionIncludeMembershipRule -Name $Collection8.Name -IncludeCollectionName $collection2.name
Write-host *** Collection $Collection8.Name created ***
New-CMDeviceCollection -Name $Collection9.Name -Comment "Endpoint Protection Policy for Test Workstations" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection9.Name created ***
New-CMDeviceCollection -Name $Collection10.Name -Comment "Endpoint Protection Policy for PROD servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionIncludeMembershipRule -Name $Collection10.Name -IncludeCollectionName $collection1.name
Write-host *** Collection $Collection10.Name created ***
New-CMDeviceCollection -Name $Collection11.Name -Comment "Endpoint Protection Policy for Test Servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection11.Name created ***
New-CMDeviceCollection -Name $Collection12.Name -Comment "All physical servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection12.Name -QueryExpression $Collection12.Query -RuleName $Collection12.Name
Write-host *** Collection $Collection12.Name created ***
New-CMDeviceCollection -Name $Collection13.Name -Comment "All virtual servers" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection13.Name -QueryExpression $Collection13.Query -RuleName $Collection13.Name
Write-host *** Collection $Collection13.Name created ***
New-CMDeviceCollection -Name $Collection14.Name -Comment "All servers with Windows 2008 or 2008 R2 operating system" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection14.Name -QueryExpression $Collection14.Query -RuleName $Collection14.Name
Write-host *** Collection $Collection14.Name created ***
New-CMDeviceCollection -Name $Collection15.Name -Comment "All servers with Windows 2012 or 2012 R2 operating system" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection15.Name -QueryExpression $Collection15.Query -RuleName $Collection15.Name
Write-host *** Collection $Collection15.Name created ***
New-CMDeviceCollection -Name $Collection16.Name -Comment "All servers with Windows 2003 or 2003 R2 operating system" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection16.Name -QueryExpression $Collection16.Query -RuleName $Collection16.Name
Write-host *** Collection $Collection16.Name created ***
New-CMDeviceCollection -Name $Collection17.Name -Comment "All servers with Windows 2016" -LimitingCollectionName $LimitingCollectionAllServer -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection17.Name -QueryExpression $Collection17.Query -RuleName $Collection17.Name
Write-host *** Collection $Collection17.Name created ***
New-CMDeviceCollection -Name $Collection18.Name -Comment "All workstations with Windows 7 operating system" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection18.Name -QueryExpression $Collection18.Query -RuleName $Collection18.Name
Write-host *** Collection $Collection18.Name created ***
New-CMDeviceCollection -Name $Collection19.Name -Comment "All workstations with Windows 8 operating system" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection19.Name -QueryExpression $Collection19.Query -RuleName $Collection19.Name
Write-host *** Collection $Collection19.Name created ***
New-CMDeviceCollection -Name $Collection20.Name -Comment "All workstations with Windows 8.1 operating system" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection20.Name -QueryExpression $Collection20.Query -RuleName $Collection20.Name
Write-host *** Collection $Collection20.Name created ***
New-CMDeviceCollection -Name $Collection21.Name -Comment "All workstations with Windows XP operating system" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection21.Name -QueryExpression $Collection21.Query -RuleName $Collection21.Name
Write-host *** Collection $Collection21.Name created ***
New-CMDeviceCollection -Name $Collection22.Name -Comment "All systems with SCCM console installed" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection22.Name -QueryExpression $Collection22.Query -RuleName $Collection22.Name
Write-host *** Collection $Collection22.Name created ***
New-CMDeviceCollection -Name $Collection23.Name -Comment "SCCM client version 1710" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection23.Name -QueryExpression $Collection23.Query -RuleName $Collection23.Name
Write-host *** Collection $Collection23.Name created ***
New-CMDeviceCollection -Name $Collection24.Name -Comment "All Dell Laptops" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection24.Name -QueryExpression $Collection24.Query -RuleName $Collection24.Name
Write-host *** Collection $Collection24.Name created ***
New-CMDeviceCollection -Name $Collection25.Name -Comment "All Lenovo laptops" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection25.Name -QueryExpression $Collection25.Query -RuleName $Collection25.Name
Write-host *** Collection $Collection25.Name created ***
New-CMDeviceCollection -Name $Collection26.Name -Comment "All HP Laptops" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection26.Name -QueryExpression $Collection26.Query -RuleName $Collection26.Name
Write-host *** Collection $Collection26.Name created ***
New-CMDeviceCollection -Name $Collection27.Name -Comment "All Microsoft Surface 4" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection27.Name -QueryExpression $Collection27.Query -RuleName $Collection27.Name
Write-host *** Collection $Collection27.Name created ***
New-CMDeviceCollection -Name $Collection28.Name -Comment "All workstations with Windows 10 operating system" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection28.Name -QueryExpression $Collection28.Query -RuleName $Collection28.Name
Write-host *** Collection $Collection28.Name created ***
New-CMDeviceCollection -Name $Collection29.Name -Comment "OSD Collection for Windows 10 deployment in production" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection29.Name created ***
New-CMDeviceCollection -Name $Collection30.Name -Comment "OSD collection to test deployment of Windows 10. Limited to admins only" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection30.Name created ***
New-CMDeviceCollection -Name $Collection31.Name -Comment "Software Update collection to exclude computers from all Software Update collections. Manual Membership" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection31.Name created ***
New-CMDeviceCollection -Name $Collection32.Name -Comment "Software Update collection for Pilote group. Manual membership" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionExcludeMembershipRule -Name $Collection32.Name -ExcludeCollectionName $collection31.name
Write-host *** Collection $Collection32.Name created ***
New-CMDeviceCollection -Name $Collection33.Name -Comment "Software Update collection for test group. Manual membership" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionExcludeMembershipRule -Name $Collection33.Name -ExcludeCollectionName $collection31.name
Write-host *** Collection $Collection33.Name created ***
New-CMDeviceCollection -Name $Collection34.Name -Comment "Software Update collection for Production. All workstations" -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionIncludeMembershipRule -Name $Collection34.Name -IncludeCollectionName $collection2.name
Add-CMDeviceCollectionExcludeMembershipRule -Name $Collection34.Name -ExcludeCollectionName $collection31.name
Write-host *** Collection $Collection34.Name created ***
New-CMDeviceCollection -Name $Collection35.Name -Comment "Collection for deployment of Office 365 production" -LimitingCollectionName $LimitingCollectionAllWork -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection35.Name created ***
New-CMDeviceCollection -Name $Collection36.Name -Comment "Test Collection for deployment of Office 365. Limited to admins only." -LimitingCollectionName $LimitingCollectionAllWorkAdmin -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Write-host *** Collection $Collection36.Name created ***
#Move the collection to the right folder
#Master Collections
$FolderPath = $SiteCode.name+":\DeviceCollection\Master Collections"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection1.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection2.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection3.Name)
#MC - Clients Settings
$FolderPath = $SiteCode.name+":\DeviceCollection\Master Collections\MC - Client Settings"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection4.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection5.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection6.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection7.Name)
#MC - Endpoint Protection
$FolderPath = $SiteCode.name+":\DeviceCollection\Master Collections\MC - Endpoint Protection"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection8.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection9.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection10.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection11.Name)
#Servers\SRV - Inventory\SRV - Hardware
$FolderPath = $SiteCode.name+":\DeviceCollection\Servers\SRV - Inventory\SRV - Hardware"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection12.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection13.Name)
#Servers\SRV - Inventory\SRV - Operating System
$FolderPath = $SiteCode.name+":\DeviceCollection\Servers\SRV - Inventory\SRV - Operating System"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection14.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection15.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection16.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection17.Name)
#Workstations\WKS - Inventory\WKS - Operating System
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory\WKS - Operating System"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection18.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection19.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection20.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection21.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection28.Name)
#Workstations\WKS - Inventory\WKS - Software
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory\WKS - Software"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection22.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection23.Name)
#Workstations\WKS - Inventory\WKS - Hardware
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - Inventory\WKS - Hardware"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection24.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection25.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection26.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection27.Name)
#Workstations\OS Deployment
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - OS Deployment"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection29.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection30.Name)
#Workstations\Software Update
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - Software Update"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection31.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection32.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection33.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection34.Name)
#Workstations\Software Distribution
$FolderPath = $SiteCode.name+":\DeviceCollection\Workstations\WKS - Software Distribution"
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection35.Name)
Move-CMObject -FolderPath $FolderPath -InputObject (Get-CMDeviceCollection -Name $Collection36.Name)

View File

@@ -0,0 +1,231 @@
# ===============================================
# Script to decline superseeded updates in WSUS.
# ===============================================
# It's recommended to run the script with the -SkipDecline switch to see how many superseded updates are in WSUS and to TAKE A BACKUP OF THE SUSDB before declining the updates.
# Parameters:
# $UpdateServer = Specify WSUS Server Name
# $UseSSL = Specify whether WSUS Server is configured to use SSL
# $Port = Specify WSUS Server Port
# $SkipDecline = Specify this to do a test run and get a summary of how many superseded updates we have
# $DeclineLastLevelOnly = Specify whether to decline all superseded updates or only last level superseded updates
# $ExclusionPeriod = Specify the number of days between today and the release date for which the superseded updates must not be declined. Eg, if you want to keep superseded updates published within the last 2 months, specify a value of 60 (days)
# Supersedence chain could have multiple updates.
# For example, Update1 supersedes Update2. Update2 supersedes Update3. In this scenario, the Last Level in the supersedence chain is Update3.
# To decline only the last level updates in the supersedence chain, specify the DeclineLastLevelOnly switch
# Usage:
# =======
# To do a test run against WSUS Server without SSL
# Decline-SupersededUpdates.ps1 -UpdateServer SERVERNAME -Port 8530 -SkipDecline
# To do a test run against WSUS Server using SSL
# Decline-SupersededUpdates.ps1 -UpdateServer SERVERNAME -UseSSL -Port 8531 -SkipDecline
# To decline all superseded updates on the WSUS Server using SSL
# Decline-SupersededUpdates.ps1 -UpdateServer SERVERNAME -UseSSL -Port 8531
# To decline only Last Level superseded updates on the WSUS Server using SSL
# Decline-SupersededUpdates.ps1 -UpdateServer SERVERNAME -UseSSL -Port 8531 -DeclineLastLevelOnly
# To decline all superseded updates on the WSUS Server using SSL but keep superseded updates published within the last 2 months (60 days)
# Decline-SupersededUpdates.ps1 -UpdateServer SERVERNAME -UseSSL -Port 8531 -ExclusionPeriod 60
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string] $UpdateServer,
[Parameter(Mandatory=$False)]
[switch] $UseSSL,
[Parameter(Mandatory=$True, Position=2)]
$Port,
[switch] $SkipDecline,
[switch] $DeclineLastLevelOnly,
[Parameter(Mandatory=$False)]
[int] $ExclusionPeriod = 0
)
Write-Host ""
if ($SkipDecline -and $DeclineLastLevelOnly) {
Write-Host "Using SkipDecline and DeclineLastLevelOnly switches together is not allowed."
Write-Host ""
return
}
$outPath = Split-Path $script:MyInvocation.MyCommand.Path
$outSupersededList = Join-Path $outPath "SupersededUpdates.csv"
$outSupersededListBackup = Join-Path $outPath "SupersededUpdatesBackup.csv"
"UpdateID, RevisionNumber, Title, KBArticle, SecurityBulletin, LastLevel" | Out-File $outSupersededList
try {
if ($UseSSL) {
Write-Host "Connecting to WSUS server $UpdateServer on Port $Port using SSL... " -NoNewLine
} Else {
Write-Host "Connecting to WSUS server $UpdateServer on Port $Port... " -NoNewLine
}
[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($UpdateServer, $UseSSL, $Port);
}
catch [System.Exception]
{
Write-Host "Failed to connect."
Write-Host "Error:" $_.Exception.Message
Write-Host "Please make sure that WSUS Admin Console is installed on this machine"
Write-Host ""
$wsus = $null
}
if ($wsus -eq $null) { return }
Write-Host "Connected."
$countAllUpdates = 0
$countSupersededAll = 0
$countSupersededLastLevel = 0
$countSupersededExclusionPeriod = 0
$countSupersededLastLevelExclusionPeriod = 0
$countDeclined = 0
Write-Host "Getting a list of all updates... " -NoNewLine
try {
$allUpdates = $wsus.GetUpdates()
}
catch [System.Exception]
{
Write-Host "Failed to get updates."
Write-Host "Error:" $_.Exception.Message
Write-Host "If this operation timed out, please decline the superseded updates from the WSUS Console manually."
Write-Host ""
return
}
Write-Host "Done"
Write-Host "Parsing the list of updates... " -NoNewLine
foreach($update in $allUpdates) {
$countAllUpdates++
if ($update.IsDeclined) {
$countDeclined++
}
if (!$update.IsDeclined -and $update.IsSuperseded) {
$countSupersededAll++
if (!$update.HasSupersededUpdates) {
$countSupersededLastLevel++
}
if ($update.CreationDate -lt (get-date).AddDays(-$ExclusionPeriod)) {
$countSupersededExclusionPeriod++
if (!$update.HasSupersededUpdates) {
$countSupersededLastLevelExclusionPeriod++
}
}
"$($update.Id.UpdateId.Guid), $($update.Id.RevisionNumber), $($update.Title), $($update.KnowledgeBaseArticles), $($update.SecurityBulletins), $($update.HasSupersededUpdates)" | Out-File $outSupersededList -Append
}
}
Write-Host "Done."
Write-Host "List of superseded updates: $outSupersededList"
Write-Host ""
Write-Host "Summary:"
Write-Host "========"
Write-Host "All Updates =" $countAllUpdates
Write-Host "Any except Declined =" ($countAllUpdates - $countDeclined)
Write-Host "All Superseded Updates =" $countSupersededAll
Write-Host " Superseded Updates (Intermediate) =" ($countSupersededAll - $countSupersededLastLevel)
Write-Host " Superseded Updates (Last Level) =" $countSupersededLastLevel
Write-Host " Superseded Updates (Older than $ExclusionPeriod days) =" $countSupersededExclusionPeriod
Write-Host " Superseded Updates (Last Level Older than $ExclusionPeriod days) =" $countSupersededLastLevelExclusionPeriod
Write-Host ""
$i = 0
if (!$SkipDecline) {
Write-Host "SkipDecline flag is set to $SkipDecline. Continuing with declining updates"
$updatesDeclined = 0
if ($DeclineLastLevelOnly) {
Write-Host " DeclineLastLevel is set to True. Only declining last level superseded updates."
foreach ($update in $allUpdates) {
if (!$update.IsDeclined -and $update.IsSuperseded -and !$update.HasSupersededUpdates) {
if ($update.CreationDate -lt (get-date).AddDays(-$ExclusionPeriod)) {
$i++
$percentComplete = "{0:N2}" -f (($updatesDeclined/$countSupersededLastLevelExclusionPeriod) * 100)
Write-Progress -Activity "Declining Updates" -Status "Declining update #$i/$countSupersededLastLevelExclusionPeriod - $($update.Id.UpdateId.Guid)" -PercentComplete $percentComplete -CurrentOperation "$($percentComplete)% complete"
try
{
$update.Decline()
$updatesDeclined++
}
catch [System.Exception]
{
Write-Host "Failed to decline update $($update.Id.UpdateId.Guid). Error:" $_.Exception.Message
}
}
}
}
}
else {
Write-Host " DeclineLastLevel is set to False. Declining all superseded updates."
foreach ($update in $allUpdates) {
if (!$update.IsDeclined -and $update.IsSuperseded) {
if ($update.CreationDate -lt (get-date).AddDays(-$ExclusionPeriod)) {
$i++
$percentComplete = "{0:N2}" -f (($updatesDeclined/$countSupersededAll) * 100)
Write-Progress -Activity "Declining Updates" -Status "Declining update #$i/$countSupersededAll - $($update.Id.UpdateId.Guid)" -PercentComplete $percentComplete -CurrentOperation "$($percentComplete)% complete"
try
{
$update.Decline()
$updatesDeclined++
}
catch [System.Exception]
{
Write-Host "Failed to decline update $($update.Id.UpdateId.Guid). Error:" $_.Exception.Message
}
}
}
}
}
Write-Host " Declined $updatesDeclined updates."
if ($updatesDeclined -ne 0) {
Copy-Item -Path $outSupersededList -Destination $outSupersededListBackup -Force
Write-Host " Backed up list of superseded updates to $outSupersededListBackup"
}
}
else {
Write-Host "SkipDecline flag is set to $SkipDecline. Skipped declining updates"
}
Write-Host ""
Write-Host "Done"
Write-Host ""

View File

@@ -0,0 +1,368 @@
# //****************************************************************************
# // ***** Script Header *****
# //
# // File: RegenerateBootImageWinPE.ps1
# //
# // Purpose: Regenerate the Configuration Manager default boot images to use
# // the latest Windows PE winpe.wim from the Windows ADK
# // The script must be used on your Primary Site Server
# //
# // Usage: powershell -ExecutionPolicy Bypass -file .\RegenerateBootImageWinPE.ps1 -BootimageName "CMBoot.wim" -BootImageConsoleName "Boot Image 1607" -OSArchitecture "x64"
# //
# // File Version: 1.0.7
# //
# // Note:
# // $PxeEnabled and $EnableDebugShell are only honored if you create new Boot Images
# // $UpdateDistributionPoints is only honored if you OverwriteExistingImage is set to $True
# //
# //
# // ***** End Header *****
# //****************************************************************************
# ***** Disclaimer *****
# This file is provided "AS IS" with no warranties, confers no rights,
# and is not supported by the authors or Microsoft Corporation.
 
### Static Parameters
[CmdLetBinding()]
Param
(
[Parameter(Mandatory = $true,
HelpMessage='Change the name matching your personal preference - Example: CMBootImage.wim')]
[ValidateScript({$_.EndsWith(".wim")})]
[String]$BootImageName,
[Parameter(Mandatory = $true,
HelpMessage='Change the name matching your personal preference - Example: "Boot Image 1607"')]
[String]$BootImageConsoleName,
[Parameter(Mandatory = $true,
HelpMessage='Change the name matching your personal preference - Example: "Boot Image based on Windows 10 1607"')]
[AllowEmptyString()]
[String]$BootImageConsoleDescription,
[Parameter(Mandatory = $true,
HelpMessage='Just cosmetics to display the OS version of your boot image. If this is "" we copy OS version as new version name')]
[AllowEmptyString()]
[String]$BootImageConsoleVersion,
[Parameter(Mandatory = $true,
HelpMessage="Provide the Boote Image Architecture - Valid Values x86, x64 or Both")]
[ValidateSet("x86","x64","Both")]
[String]$OSArchitecture,
[Parameter(Mandatory = $true,
HelpMessage='Valid Values True/False - Set to True if you want to enable Command Command support on your new created boot images (applies only to new created boot images)')]
[ValidateSet('True','False')]
[String]$EnableDebugShell,
[Parameter(Mandatory = $true,
HelpMessage='Valid Values True/False -Set to True if the new created boot image should be enabled to be deployed from PXE enabled DP (applies only to new created boot images)')]
[ValidateSet('True','False')]
[String]$PxeEnabled,
[Parameter(Mandatory = $true,
HelpMessage='Valid Values True/False - Set to $True if you want to replace an existing boot image')]
[ValidateSet('True','False')]
[String]$OverwriteExistingImage,
[Parameter(Mandatory = $true,
HelpMessage='Valid Values True/False - Set to $True if you want update Distribution Point (applies only if $OverwriteExistingImage = $True and the script detects an existing boot image matching $BootImageName)')]
[ValidateSet('True','False')]
[String]$UpdateDistributionPoints
)
### Convert necessary Parameter to Boolean - the Param-Strings were used to simplify the Input in the Beginning
Switch ($EnableDebugShell)
{
"True" {[Boolean]$EnableDebugShell = $true; Break}
"False" {[Boolean]$EnableDebugShell = $false; Break}
}
Switch ($PxeEnabled)
{
"True" {[Boolean]$PxeEnabled = $true; Break}
"False" {[Boolean]$PxeEnabled = $false; Break}
}
Switch ($OverwriteExistingImage)
{
"True" {[Boolean]$OverwriteExistingImage = $true; Break}
"False" {[Boolean]$OverwriteExistingImage = $false; Break}
}
Switch ($UpdateDistributionPoints)
{
"True" {[Boolean]$UpdateDistributionPoints = $true; Break}
"False" {[Boolean]$UpdateDistributionPoints = $false; Break}
}
 
### Logging - Static Paramter can be changed
 
[String]$LogfileName = "RegenerateBootImageWinPE"
[String]$Logfile = "$env:SystemRoot\logs\$LogfileName.log"
 
Function Write-Log
{
Param ([string]$logstring)
If (Test-Path $Logfile)
{
If ((Get-Item $Logfile).Length -gt 2MB)
{
Rename-Item $Logfile $Logfile".bak" -Force
}
}
$WriteLine = (Get-Date).ToString() + " " + $logstring
Add-content $Logfile -value $WriteLine
Write-Host $WriteLine
}
 
### Verify access to Configuration Manager Console for a PowerShell Commandlet import
 
Try
{
$ConfigMgrModule = ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1')
Import-Module $ConfigMgrModule
Write-Log "Found SCCM-Console-Environment"
Write-Log $ConfigMgrModule
}
Catch
{
Write-host "Exception Type: $($_.Exception.GetType().FullName)"
Write-host "Exception Message: $($_.Exception.Message)"
Write-Host "ERROR! Console not installed or found"
Write-Host "Script will exit"
Exit 1
}
### Get Site-Code and Site-Provider-Machine from WMI if possible
Try
{
$SMS = gwmi -Namespace 'root\sms' -query "SELECT SiteCode,Machine FROM SMS_ProviderLocation"
$SiteCode = $SMS.SiteCode
$SccmServer = $SMS.Machine
Write-Log "SiteCode: $SiteCode"
Write-Log "SiteServer: $SccmServer"
}
Catch
{
Write-Log "Exception Type: $($_.Exception.GetType().FullName)"
Write-Log "Exception Message: $($_.Exception.Message)"
Write-Log "Unable to find in WMI SMS_ProviderLocation. This Script has to run on a SiteServer!"
Exit 1
}
### Change to CM-Powershell-Drive
 
Write-Log "Prepare Environment for Boot Image operations. Create PS-Drive if not found."
$CMDrive = Get-PSProvider -PSProvider CMSite
If ($CMDrive.Drives.Count -eq 0)
{
Write-Log "CMSite-Provider does not have a Drive! Try to create it."
Try
{
New-PSDrive -Name $SiteCode -PSProvider CMSite -Root $SiteProvider
Write-Log "CMSite-Provider-Drive created!"
}
Catch
{
Write-Log "Exception Type: $($_.Exception.GetType().FullName)"
Write-Log "Exception Message: $($_.Exception.Message)"
}
}
### ReCreate BootImage Function
Function funCreateBootImage
{
[CmdLetBinding()]
Param
(
[Parameter(Mandatory = $True)]
[ValidateSet("x86","x64")]
[string]$Architecture
)
Switch ($Architecture)
{
"x86" {$ArchitecturePath = "i386"; Break}
"x64" {$ArchitecturePath = "x64"; Break}
}
Write-Log "Connecting to WMI Namespace: \\$SccmServer\root\sms\site_$SiteCode`:SMS_BootImagePackage"
$BootImageWMIClass = [wmiclass]"\\$SccmServer\root\sms\site_$SiteCode`:SMS_BootImagePackage"
[String]$BootImageSourcePath = "\\$SccmServer\SMS_$SiteCode`\OSD\boot\$ArchitecturePath\$BootImageName"
If($(Get-Location) -match $SiteCode)
{
Write-Log "Switching Drive to File System"
Set-Location "C:"
}
If (Test-Path -Path $BootImageSourcePath -PathType Leaf)
{
If(!$OverwriteExistingImage)
{
Write-Log "Error: $BootImageSourcePath found and OverwriteExistingImage is set to `$False"
# Critical Error occured exit function
break
}
Write-Log "$BootImageSourcePath found need to backup first"
Copy-Item $BootImageSourcePath $BootImageSourcePath".bak" -Force
[boolean]$BootImageFound = $True
}
Else
{
Write-Log "$BootImageSourcePath not found no need to backup"
}
Try
{
Write-Log "Generating $Architecture Boot Image. This will take a few minutes... "
$BootImageWMIClass.ExportDefaultBootImage($Architecture , 1, $BootImageSourcePath) | Out-Null
Write-Log "New $Architecture Boot Image created continue with post tasks "
$NewBootImageName = "$BootImageConsoleName ($Architecture)"
If(-not($BootImageFound))
{
# Actions to perform if Boot Image file did not exist
Write-Log "Performing actions section Boot Image not exist"
If(-not($(Get-Location) -match $SiteCode))
{
Write-Log "Switching Drive for ConfigMgr-CmdLets"
Set-Location $SiteCode":"
}
Try
{
Write-Log "Import Boot Image into SCCM"
If($BootImageConsoleDescription.Length -eq 0)
{
New-CMBootImage -Path $BootImageSourcePath -Index 1 -Name $NewBootImageName -Version $BootImageConsoleVersion | Out-Null
Write-Log "Successfully imported $BootImageSourcePath"
}
Else
{
New-CMBootImage -Path $BootImageSourcePath -Index 1 -Name $NewBootImageName -Version $BootImageConsoleVersion -Description $BootImageConsoleDescription | Out-Null
Write-Log "Successfully imported $BootImageSourcePath"
}
}
Catch
{
Write-Log "Error: Failed to import $BootImageSourcePath"
# Critical Error occured exit function
break
}
Try
{
If($BootImageConsoleVersion.Length -eq 0)
{
Write-Log "Get Boot Image Property ImageOSVersion"
$BootImageConsoleVersion = (Get-CMBootImage -Name $NewBootImageName).ImageOSVersion
}
Write-Log "Apply Boot Image Properties EnableCommandSupport with Value $EnableDebugShell and DeployFromPxeDistributionPoint with Value $PxeEnabled"
Set-CMBootImage -Name $NewBootImageName -EnableCommandSupport $EnableDebugShell -DeployFromPxeDistributionPoint $PxeEnabled -Version $BootImageConsoleVersion
Write-Log "Successfully applied Boot image properties"
}
Catch
{
Write-Log "Failed to apply Boot image properties"
}
}
Else
{
# Actions to perform if Boot Image file did exist
Write-Log "Performing actions section Boot Image did exist"
$BootImageQuery = Get-WmiObject -Class SMS_BootImagePackage -Namespace root\sms\site_$($SiteCode) -ComputerName $SccmServer | where-object{$_.ImagePath -like "*$ArchitecturePath*" -and $_.ImagePath -like "*$BootImageName*"}
ForEach($BootImagexIndex in $BootImageQuery)
{
$BootImageLogName = $BootImagexIndex.Name
Write-Log "Working on Boot Image: $BootImageLogName"
# Verify if the current Site is owner of this Boot Image (Unneeded in single Primary Site environments)
If($BootImagexIndex.SourceSite -ne $SiteCode)
{
Write-Log "Error: Site is not owner of this Boot Image $BootImageLogName will stop post actions"
}
Else
{
If($BootImageConsoleVersion.Length -eq 0)
{
$BootImageConsoleVersion = $BootImagexIndex.ImageOSVersion
}
$BootImagexIndexVersion = $BootImagexIndex.Version
Write-Log "Will use version: $BootImageConsoleVersion as Version value"
}
$BootImage = Get-WmiObject -Class SMS_BootImagePackage -Namespace root\sms\site_$SiteCode -ComputerName $SccmServer | where-object{$_.Name -like "*$BootImageLogName*"}
Try
{
Write-Log "Reload Image Properties to update console with new information"
$BootImage.ReloadImageProperties() | Out-Null
}
Catch
{
Write-Log "Error: Failed to Reload Image Properties to update console with new information"
}
If($UpdateDistributionPoints)
{
Try
{
Write-Log "Trigger update Distribution Points"
$BootImage.UpdateImage | Out-Null
}
Catch
{
Write-Log "Error: Failed to Trigger update Distribution Points"
}
}
If(-not($(Get-Location) -match $SiteCode))
{
Write-Log "Switching Drive for ConfigMgr-CmdLets"
Set-Location $SiteCode":"
}
Try
{
Write-Log "Apply Boot Image Properties for Version with Value $BootImageConsoleVersion"
Set-CMBootImage -Name $BootImageLogName -Version $BootImageConsoleVersion
Write-Log "Successfully applied Boot image properties"
}
Catch
{
Write-Log "Failed to apply Boot image properties"
}
}
}
}
Catch
{
Write-Log "Error: Failed to create $Architecture Boot Image. Exit $Architecture Boot Image post taks "
# Critical Error occured exit function
break
}
$BootImageFound = $False
}
Write-Log "Trying to generate Boot images"
Switch ($OSArchitecture)
{
"x86" {funCreateBootImage -Architecture x86;Break}
"x64" {funCreateBootImage -Architecture x64;Break}
"Both" {
funCreateBootImage -Architecture x86
funCreateBootImage -Architecture x64
;Break
}
}

View File

@@ -0,0 +1 @@
C:\Users\Admin\Desktop\client-SCCM\ccmsetup.exe /forceinstall /forcereboot /source:C:\Users\Admin\Desktop\client-SCCM /mp:sccm.iut.local SMSSITECODE=IUT SMSMP=SCCM.iut.local DNSSUFFIX=iut.local

488
Sauve-aubrac.ps1 Normal file
View File

@@ -0,0 +1,488 @@
# =======================================================
# Fonction qui ecrit les messages sur la sortie standard
# Usage : Write-OutputConsole ($theme)
# =======================================================
function Write-OutputConsole($theme) {
if ( $theme -eq "lancement") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde en local de Vos Documents et de Votre Bureau est en cours. !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "lancementvol") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde sur Serveur distant de D:\ est en cours. !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .DS_Store thumbs.db !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "zipprob") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La compression de la messagerie a echoué !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "nospace") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Disque dur C Local n'a pas assez d'espace Libre !"
Write-Output "! !"
Write-Output "! La sauvegarde est annulée !"
Write-Output "! Contactez votre administrateur. !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "novoltaire") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Serveur de Sauvegarde est indiponible !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! La Sauvegarde distante est Annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagloc") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Locale de Vos Documents e tde Votre Bureau a déjà été lancée !"
Write-Output "! !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagnet") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Réseau de Vos Documents et de Votre Bureau !"
Write-Output "! a déjà été lancée !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
}
# =======================================================
# Fonction qui envoie un email avec 2 attachements
# =======================================================
function Send-EMail($argFrom, $argTo, $argtoCC, $argPriority, $argSubject, $argBody, $argAtt, $argSmtp) {
$mail = New-Object System.Net.Mail.MailMessage
$smtpClient = new-object system.net.mail.SmtpClient($argSmtp)
$mail.Body = $argBody
$mail.Subject = $argSubject
$mail.priority = $argPriority
$mail.From = $argFrom
$mail.To.Add($argTo)
if ($argtoCC) {
$mail.CC.Add($argtoCC)
}
if (!($argAtt -eq $null)) {
$att = new-object Net.Mail.Attachment $argAtt
$mail.Attachments.Add($att)
}
$smtpClient.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$smtpClient.Send($mail)
$mail.Attachments.Dispose()
$mail = $null
$smtpClient = $null
}
# =======================================================================
# Fonction qui affiche une boite de dialogue qui se ferme automatiquement
# =======================================================================
function DisplayMessageBox($argText, $argDelayDisplay, $argTitre, $argButton) {
$job=Start-Job -ArgumentList $argText,$argDelayDisplay,$argTitre,$argButton -ScriptBlock {
$a = new-object -comobject wscript.shell
$a.popup($args[0],$args[1],$args[2],$args[3])
}
return $job;
}
# =================================================================================================
# DESCRIPTION: Displays the attention message box & checks to see if the user clicks the ok button.
# Affiche une boîte de dialogue fenêtrée
# Prérequis [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# =================================================================================================
function Show-MessageBox([string] $Message,[string] $Titre="Attention !!", [String] $IconType="Warning",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
function Show-QuestionBox([string] $Message,[string] $Titre="Question ??", [String] $IconType="Question",[String] $BtnType="YesNo") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre,[Windows.Forms.MessageBoxButtons]::$BtnType, [Windows.Forms.MessageBoxIcon]::$IconType)
}
function Show-InfoBox([string] $Message,[string] $Titre="Pour votre Information !!", [String] $IconType="Information",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
# =================================================
# Renvoi la Taille d'un repertoire en octets
# =================================================
function Get-FolderSize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
# =================================================
# Renvoi la Taille d'un fichier en octet
# =================================================
function Get-FileSize($Path) {
# On verifie si le path exist
if(test-path $Path){
$colItems = (Get-ChildItem $Path)
return $colItems.Length
}
else {
return 0
}
}
# ==================================================
# Renvoie la Taille d'un fichier en Go
# ==================================================
function Get-FileSizeGB($Path){
return ("{0:N2}" -f ((Get-FileSize $Path) /1GB))
}
# ===========================================================
# Nettoyage des Logs
# ===========================================================
function Delete-Logs($argDirectoryLogs,$argDelay){
$jour = [DateTime]::Today
$lastMod = $jour.AddDays(-$argDelay)
#Récupere la liste des fichiers logs antérieurs à la date
$Files = get-childitem $argDirectoryLogs -include *.log -recurse | Where {$_.LastWriteTime -le "$lastMod"}
if (!($Files -eq $null)) {
foreach ($File in $Files) {
write-host $File
Remove-Item $File
}
}
}
# =========================================================================
# Fonction de récupération du mail utilisateur dans le fichier sur Voltaire
# =========================================================================
function Get-Email {
param ([string]$login,[string]$filelogs)
Get-Content $filelogs | Where-Object { $_.split(";")[0] -match "$login"} | foreach {$_ -replace "^$login;", ""}
}
# =======================================================
# Fonction qui initialise le bon path de la messagerie
# =======================================================
function Find-DirectoryMessagerie {
param ([string]$pathDocsUserLocation)
Set-Location $pathDocsUserLocation
Get-ChildItem "./" | Where-Object {$_.Attributes -eq "Directory"} | Where-Object {$_.Name -match "^[M-m]essagerie$"} | foreach {$_.FullName}
}
# =========================================================================
# Fonctions relatives à la taille du disque C
# =========================================================================
function Get-FreeSpaceCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace/1GB,2)}
}
function Get-FreeSpaceC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
}
function Get-SizeC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
}
function Get-SizeCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size/1GB,2)}
}
function espacedispo
{
$freespaceC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
$sizeC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
$freespaceCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace / 1073741824,2)}
$sizeCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size / 1073741824,2)}
$docspace = (Get-FolderSize $DocsUserLocation).Sum
$burspace = (Get-FolderSize $BureauUserLocation).Sum
$totaltoback = $burspace + $docspace
$docspaceGB = [Math]::round($docspace/1GB,2)
$totaltobackGB = [Math]::round($totaltoback/1GB,2)
$spaceminfree = $totaltoback + 21474836480
echo $spaceminfree
echo $freespaceCGB
if
( $freespaceC -lt $spaceminfree )
{
$greenflag = 1
}
else
{
$greenflag = 0
}
return $greenflag
}
function Kill-Process ($app) {
if (Get-Process $app -ErrorAction silentlycontinue) {
Get-Process $app | Stop-Process
Start-Sleep -s 2
}
}
function Get-OS {
return (Get-WmiObject -class Win32_OperatingSystem).Caption | foreach {$_ -replace " ", ""}
}
#=======================================================
# Fonction qui défini laptop ou desktop
# =======================================================
function Get-PCtype {
return (Get-WmiObject -class Win32_computersystem).PCSystemType }
$pctype = Get-PCtype
if ($pctype -ne "2")
{$fixe = "Oui"}
else
{$fixe = "Non"}
# =======================================================
# Fonction qui écrit des indicateurs dans un fichier
# =======================================================
function Set-Indicator($fichier) {
#Si le fichier n'existe pas, je crée un nouveau fichier.
if ((Test-Path $fichier) -ne "True") { New-Item -ItemType file -Path $indicateurs -Force }
# Ajoute une ligne dans le fichier.
# Les champs sont l'utilisateur, l'ordinateur, les 5 codes de sortie des commandes robocopy, les dates de debut et de fin, la taille en GB à copier à distance
# et l'espace libre suffisant Oui ou Non
Add-Content -Path $fichier -Value "$UserName;$ComputerName;$DocExitCode;$BurExitCode;$BurVolExitCode;$DocVolExitCode;$Tstart;$Tend;$sizetobackGB;$nospace"
}
# =======================================================
# Déclaration des variables globales
# =======================================================
# Portable ou Fixe
#$fixe = "Oui"
# Serveur de backup
$BackupServer = "DRACNEW"
# Serveur de Backup FQDN
$BackupServerfdqn = "DRACNEW.iut.local"
# Répertoire partagé sur le serveur
$ShareBackupServer = "AUBRAC"
# Nom de l'ordinateur
$ComputerName = $Env:COMPUTERNAME
# Emplacement des donnees a sauver
$DirectoryBackup = "D:\"
# Repertoire a exclure
$DirectoryExclude = "D:\A_Supprimer"
$DirectoryExclude1 = "*Profil.V6"
$DirectoryExclude2 = "*Profil.V2"
$DirectoryExclude3 = "*cache*"
#$DirectoryExclude4 = "D:\'$RECYCLE'.BIN"
# Nom de la session
$UserName = "Administrateur"
# Initialisation du jour de la semaine
$numjour = Get-Date -UFormat %u
# Initialisation du Jour de l'année
$dayofyear = (get-date).dayofyear
# Répertoire de sauvegarde sur le serveur aubrac
$DirBackVol = "\\$BackupServerfdqn\$ShareBackupServer\"
# Nom du repertoire de logs
$NameDirectoryLogs = "logssauv"
# Nom du repertoire de logs Local
$NameDirectoryLogsLocal = "localogssauv"
# Nom du serveur smtp
$SmtpServerName = "relay.iut-rodez.fr"
# Mail du support
$toSupport = "support@iut-rodez.fr"
# Emplacement du fichier de correspondance des emails (attention à ce qu'il ne soit pas modifié par des utilisateurs!)
$filelogins = "C:\users\administrateur.IUT\logssauv\login-emails.txt"
# Champ FROM des courriel
if ((Test-Path $filelogins) -ne "True") {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
$mailfrom = Get-EMail $UserName $filelogins
}
}
if ((Test-Path $filelogins) -ne "True") {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
$Toclient = Get-EMail $UserName $filelogins
}
}
# Fichier des indicateurs sur \\aubrac
$indicateurs = "c:\users\administrateur.IUT\logssauv\indicateurs$dayofyear.txt"
# Localisation du profil des utilisateurs (XP ou seven)
$NameDirectoryLogs = "C:\users\administrateur.IUT\logssauv"
$fichierflagnet = "$DirectoryBackup\flag-net.txt"
$os = Get-OS
#Liste des fichiers à exclure
$FileExclude = "`"*.DS_Store`" `".DS_Store`" `"*thumbs.db`" "
# Nom du fichier logs
$NameDocVolLogs = "SavDocAubrac"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$DelayRetentionLogs = 8
$listJob = @()
$ExitCode = @{
"16"="Erreur fatale lors de l'opération. Voir fichier de Log"
"15"="Echec de la copie. Voir le fichier de Log."
"14"="Echec de la copie. Voir le fichier de Log."
"13"="Echec de la copie. Voir le fichier de Log."
"12"="Echec de la copie. Voir le fichier de Log."
"11"="Echec de la copie. Voir le fichier de Log."
"10"="Echec de la copie. Voir le fichier de Log."
"9"="Echec de la copie. Voir le fichier de Log."
"8"="Echec de la copie. Plisieurs fichiers n'ont pas été copiés. Voir le fichier de Log."
"7"="Copie OK. Certains fichiers présents et supplémentaires on généré une incohérence entre la source et la destination. Voir le fichier de Log."
"6"="Copie OK. Certains fichiers et dossiers suplémentaires ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"5"="Copie OK. Certains fichiers ont été copiés et d'autres ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"4"="Copie OK. Une incohérence entre la source et la destination de la sauvegarde a été détectée. Voir le fichier de Log."
"3"="Copie OK. Certains fichiers supplémentaires ont été copiés avec succès."
"2"="Copie OK. Certains fichiers ou répertoires supplémentaires ont été détectés et copiés avec succès."
"1"="Copie OK. Un ou plusieurs fichiers ont été copiés avec succès du répertoire source au répertoire de destination."
"0"="Copie OK. Aucun changement. Le répertoire source était identique au répertoire de destination."
}
$mail = New-Object System.Net.Mail.MailMessage
$killappli = @("outlook","excel","winword","powerpnt","msaccess","mspub","visio","thunderbird","soffice.bin")
$SavDocVolLog = "$NameDirectoryLogs\$NameDocVolLogs"
$resultatcopieloc = 0
$resultatcopienet = 0
$pasnecessaireloc = 0
$pasnecessairenet = 0
# FIN VARIABLES GLOBALES DEF ET INIT
# =============================
# DEBUT DU PROGRAMME PRINCIPAL
# =============================
# Chargement d'une librairie pour l'affichade de fenetre
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# On tue les appli genantes
foreach ($i in $killappli){
Kill-Process ($i)
}
Start-Sleep -s 2
$TimesStart = Get-date -Format 'dddd dd MMM yyyy'
$HourStart = Get-Date -Format 'HH"h"mm'
$Tstart = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# SEQUENCE : COPIE RESEAU
## ================================================================
Write-OutputConsole("lancementvol")
Start-Sleep -s 2
# Test de la disponibilité du serveur, on arrête le programme si le serveur est injoignable
if ((!(Test-Connection -computer $BackupServer -Count 3 -quiet)) -or (!(Test-Connection -computer $BackupServerfdqn -Count 5 -quiet))) {
Write-OutputConsole("nosynolog")
Show-MessageBox ("Attention !!", "Le serveur de backup n'est pas joignable, la sauvegarde est annulée`nContactez votre administrateur.`n`nCliquez su OK pour Eteindre")
exit
}
# Lancement de la copie de D: sur DRACNEW
robocopy "$DirectoryBackup" "$DirBackVol" /MIR /R:3 /W:5 /xf $fileExclude /XD "$DirectoryExclude" /XD "$DirectoryExclude1" /XD "$DirectoryExclude2" /XD "$DirectoryExclude3" >> $SavDocVolLog
$DocVolExitCode = $LASTEXITCODE
if ($DocVolExitCode -lt 8){
# La sauvegarde Locale est réussie, on remet le fichier flag puis on compresse le tout dans le dossier du jour
set-content -path "$fichierflagnet" -value "OK"
$resultatcopienet = 1
}
$TimesEnd = Get-date -Format 'dddd dd MMM yyyy'
$HourEnd = Get-Date -Format 'HH"h"mm'
$Tend = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# 3EME SEQUENCE : INDICATEURS/NOTIFICATIONS
# ================================================================
Delete-Logs $NameDirectoryLogs 8
if ($resultatcopienet -eq 1) {
$messagecourriel = "Résultat de la sauvegarde : OK (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Si la sauvegarde a déja été exécutée dans les 18h, elle n'est pas relancée."
$toSupport = $null
}
else {
$messagecourriel = "Un problème est survenu dans l'exécution de votre sauvegarde (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Un problème est survenu dans l'exécution de la sauvegarde pour $UserName. survenu lors de la sauvegarde de D:\ démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd.`n`nLes résultats de sauvegardes ont été les suivants :`n`nCopie de D:\ vers DRACNEW `n"+$ExitCode["$DocVolExitCode"]+"`n`Pour de plus amples détails, consultez le fichier log en pièce jointe."
}
If (!(Test-Path "$SavDocVolLog")){
$SavDocVolLog = $null
}
# Message aux utilisateurs
Send-Email $mailfrom $Toclient $toSupport 'High' $messagecourriel $body $SavDocVolLog $SmtpServerName
# TODO:verifier le lancement de la commande mail
# INDICATEURS :
# ------------
#
Set-indicator($indicateurs)
{
Exit
}

View File

@@ -0,0 +1,140 @@
$GlpiCreds = @{AppURL = "http://192.168.100.89/apirest.php";UserToken = "JSsoyIIG067IOWJG0EoJoDFtDSWs8fYgUZgVYQRo";AppToken = "4eMkSWhCanzvyOhTcVInLYhmA4c4gfdXFcCVOsRl";AuthorizationType = "user_token"}
$salle = 'A105'
$liste = Search-GlpiItem -ItemType "Computer" -SearchOptions ("AND",1,"contains","$salle"),("OR",2,"contains",""),("OR",4,"contains",""),("OR",5,"contains",""),("OR",37,"contains",""),("OR",40,"contains",""),("OR",46,"contains",""),("OR",48,"contains",""),("OR",17,"contains",""),("OR",111,"contains","") -Creds $GlpiCreds
$local = Get-iTopObject -key "SELECT Location WHERE name LIKE '%A105'" -class "Location" -OutputFields "*"
$location = $local.key
For ($i=0; $i -le $liste.Length; $i++) {
$pcglp = $liste[$i].2
echo $pcglp
$liste2 = Search-GlpiItem -ItemType "Computer" -SearchOptions ("AND",1,"contains",""),("AND",2,"contains","$pcglp"),("OR",4,"contains",""),("OR",5,"contains",""),("OR",37,"contains",""),("OR",40,"contains",""),("OR",46,"contains",""),("OR",48,"contains",""),("OR",17,"contains",""),("OR",111,"contains","") -Creds $GlpiCreds
$modele = $liste2.40
$mod = Get-iTopObject -key "SELECT Model WHERE name LIKE '%$modele%'" -class "Model" -OutputFields "*"
if (!$mod) {
Write-Host "Le modèle '$modele' ne existe pas dans iTop"
}
$pc = Get-glpiitem -itemtype Computer -id $liste2.2 -creds $GlpiCreds
$pc_id = $pc.id
$pc_serial = $pc.serial
$name = $pc.name
if (($pc.otherserial -eq $null) -or ($pc.otherserial -eq "")) { $pcserial = 'notset' } else { $pcserial = $pc.otherserial }
if (!$pc.manufacturers_id) { $brand = 10 } elseif ($pc.manufacturers_id -eq 1) {$brand = 106}
if (!$pc.computermodels_id) { $model= 150 }
elseif ($pc.computermodels_id -eq 6) {
$model = 152}
elseif ($pc.computermodels_id -eq 8) {
$model = 149}
elseif ($pc.computermodels_id -eq 10) {
$model = 176}
elseif ($pc.computermodels_id -eq 1) {
$model = 175}
if (!$liste2.46) {
$os = 8 }
elseif ($liste2.46 -eq 1803) {
$os = 146}
elseif ($liste2.46 -eq 1607) {
$os = 146}
elseif ($liste2.46 -eq 1703) {
$os = 146}
elseif ($liste2.46 -eq 1709) {
$os = 146}
elseif ($liste2.46 -eq 1809) {
$os = 146}
elseif ($liste2.46 -eq 1909) {
$os = 146}
if (!$liste2.48) {
$version = 154 }
elseif ($liste2.48 -eq '10.0.17134')
{ $version = 154}
if (!$liste2.37) {
$date2prod = $null
$garantie = $null
}
else
{ if (($liste2.37 -eq $null) -or ($liste2.37 -eq ""))
{
$date2prod = $null
$garantie = $null
}
else
{$date2prod = $liste2.37
$dateprod = [datetime]::parseexact($date2prod, 'yyyy-MM-dd', $null)
$datep = $dateprod.ToString('yyyy-M-d')
$garantie = $dateprod.AddYears(+5)
$garant = $garantie.ToString('yyyy-M-d')
}
}
if (!$liste2.17) { $cpu = "" } else { $cpu = $liste2.17 }
if (!$liste2.111) { $ram = "" } else { $ram = $liste2.111 }
if (!$liste2.4) {
$type = 'desktop' }
elseif ($liste2.4 -eq 'Laptop' ) {
$type = 'laptop' }
elseif ($liste2.4 -eq 'Desktop' ) {
$type = 'desktop' }
elseif ($liste2.4 -eq 'Mini Tower' ) {
$type = 'desktop' }
elseif ($liste2.4 -eq 'Precision 5820 Tower' ) {
$type = 'desktop' }
$pcitop = Get-iTopObject -key "SELECT PC WHERE serialnumber='$pc_serial'" -class "PC" -OutputFields "*"
if ((!$pcitop) -or ($pcitop -eq $null) -or ($pcitop -eq "")) {
if ((!$liste2.37) -or ($liste2.37 -eq $null) -or ($liste2.37 -eq "")) {
php -f CreatePC2-itop.php PC 2 $name $pc_serial $pcserial $location $brand $model $os $version $cpu $ram $type
}
else {
php -f CreatePC-itop.php PC 2 $name $pc_serial $pcserial $location $brand $model $os $version $date2prod $garant $cpu $ram $type
}
}
else {
echo $name $location $brand $model $os $version $date2prod $cpu $ram $type $garant
if ((!$liste2.37) -or ($liste2.37 -eq $null) -or ($liste2.37 -eq "")) {
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'name'=$name}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'asset_number'=$pcserial}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'location_id'=$location}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'type'=$type}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'brand_id'=$brand}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'model_id'=$model}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'cpu'=$cpu}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'osfamily_id'=$os}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'osversion_id'=$version}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'ram'=$ram}
}
else {
echo $location $brand $model $os $version $date2prod $cpu $ram $type $garant
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'name'=$name}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'asset_number'=$pcserial}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'location_id'=$location}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'type'=$type}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'brand_id'=$brand}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'model_id'=$model}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'cpu'=$cpu}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'osfamily_id'=$os}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'osversion_id'=$version}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'ram'=$ram}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'move2production'=$date2prod}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'purchase_date'=$date2prod}
Set-iTopObject -key $pcitop.key -class "PC" -Fields @{'end_of_warranty'=$garant}
Write-Host "rien à faire"
}
}
}

View File

@@ -0,0 +1,324 @@
# Let script run without admin saying yes, and run the script as admin
# Turns off error responses or turn on or what
# Here is where to turn all errors on and off
# Remove comment for Write-Output to create a log file somewhere on the local computer, or where you like
# $Postup is variable for the path to the logfile
# Enter your KMS server name
# Replace YOUR.KMS.SERVER.NAME with your KMS server name
$ErrorActionPreference = "SilentlyContinue"
#$ErrorActionPreference = "Inquire"
#$ErrorActionPreference = "Stop"
#$ErrorActionPreference = "Continue"
cls
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "Black"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
# Run your code that needs to be elevated below
Function Activate10
{
# Activate Windows 10 - Install KMS Key (Public Key @ Microsoft)
# slmgr.vbs /ipk NPPR9-FWDCX-D2C8J-H872K-2YT43
#Write-Output "Windows 10 Activation Commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output "slmgr.vbs /ipk NPPR9-FWDCX-D2C8J-H872K-2YT43" | out-file $PostUp -encoding ascii -Append -Noclobber
# Activate Windows - Point to KMS Server (Public Key @ Microsoft)
#slmgr.vbs /skms snkms.unistra.fr
#Write-Output "slmgr.vbs /skms YOUR.KMS.SERVER.NAME" | out-file $PostUp -encoding ascii -Append -Noclobber
# Activate Windows - Activate Windows
#slmgr.vbs /ato
#Write-Output "slmgr.vbs /ato" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output "End of Windows 10 Activation commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output `n | out-file $PostUp -encoding ascii -Append -Noclobber
}
Function Activate7
{
# Activate Windows - Install KMS Key Windows 7 (Public Key @ Microsoft)
#slmgr.vbs /ipk 33PXH-7Y6KF-2VJC9-XBBR8-HVTHH
#Write-Output "Windows 7 Activation Commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output "slmgr.vbs /ipk 33PXH-7Y6KF-2VJC9-XBBR8-HVTHH" | out-file $PostUp -encoding ascii -Append -Noclobber
# Activate Windows - Point to KMS Server
#slmgr.vbs /skms snkms.unistra.fr
#Write-Output "slmgr.vbs /skms YOUR.KMS.SERVER.NAME" | out-file $PostUp -encoding ascii -Append -Noclobber
# Activate Windows - Activate Windows 7
#slmgr.vbs /ato
#Write-Output "slmgr.vbs /ato" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output "End of Windows 7 Activation commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output `n | out-file $PostUp -encoding ascii -Append -Noclobber
}
Function 2013
{
# Change to Office 2013 - 32/64bit directory
CD "c:\Program Files\Microsoft Office\Office15"
#Write-Output "Activate Office commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output 'CD "c:\Program Files\Microsoft Office\Office15"' | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate Office Function
WonderTwinsPowerActivate
}
Function 20133264
{
# Change to Office 2013 32bit - 64bit OS directory
CD "c:\Program Files (x86)\Microsoft Office\Office15"
#Send Commands to log file
#Write-Output "Activate Office commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output 'CD "c:\Program Files\Microsoft Office\Office15"' | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate Office Function
WonderTwinsPowerActivate
}
Function 2016
{
# Change to Office 2016 - 32/64bit directory
CD "c:\Program Files\Microsoft Office\Office16"
#Send Commands to log file
#Write-Output "Activate Office commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output 'CD "c:\Program Files\Microsoft Office\Office16"' | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate Office Function
WonderTwinsPowerActivate
}
Function 20163264
{
# Change to Office 2016 32bit - 64bit OS directory
CD "c:\Program Files (x86)\Microsoft Office\Office16"
#Send Commands to log file
#Write-Output "Activate Office commands" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output 'CD "c:\Program Files (x86)\Microsoft Office\Office16"' | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate Office Function
WonderTwinsPowerActivate
}
Function WonderTwinsPowerActivate
{
# Activate Office All Versions - Point to KMS Server
cscript ospp.vbs /sethst:snkms.unistra.fr
#Send Commands to log file
#Write-Output 'cscript ospp.vbs /sethst:YOUR.KMS.SERVER.NAME' | out-file $PostUp -encoding ascii -Append -Noclobber
# Activate Office 2013 - Activate Office 2013
cscript ospp.vbs /act
#Send Commands to log file
#Write-Output 'cscript ospp.vbs /act' | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output 'End of Office Activation' | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output `n | out-file $PostUp -encoding ascii -Append -Noclobber
}
#Variables - CHANGE THIS!
#Remove Comment for PostUp and enter your path for where you want the log file to be
#$PostUp = "C:\Path\On\Local\Computer\To\Log\All\Commands.txt"
#Office Version Variables (Default Install locations)
$2013 = "c:\Program Files\Microsoft Office\Office15"
$20133264 = "c:\Program Files (x86)\Microsoft Office\Office15"
$2016 = "c:\Program Files\Microsoft Office\Office16"
$20163264 = "c:\Program Files (x86)\Microsoft Office\Office16"
#Script
#Create Log File - Remove Comment to use log file
#Remember to make changes for path and postup variable
<#
New-Item C:\Path\On\Local\Computer\To\Log\All\Commands.txt -type file -force
Get-date | out-file $PostUp -encoding ascii -Append -Noclobber
#>
#Check for Windows 7 or Windows 10
If (!((Get-WmiObject -class Win32_OperatingSystem -Property * | Select-Object -ExpandProperty Caption) -eq "Microsoft Windows 10 Enterprise"))
{
#Write-Output "Operating System:" "(Get-WmiObject -class Win32_OperatingSystem -Property * | Select-Object -ExpandProperty Caption)" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output `n | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate7
}
Else
{
#write-Host "Windows 10 - Hip Hop Hooray! Hooooo Haaaaay Hoooooo"
#Write-Output "Operating System:" "(Get-WmiObject -class Win32_OperatingSystem -Property * | Select-Object -ExpandProperty Caption)" | out-file $PostUp -encoding ascii -Append -Noclobber
#Write-Output `n | out-file $PostUp -encoding ascii -Append -Noclobber
#Activate10
}
#Check Office Versions
#Check for office 2013 32bit
If (Test-Path $2013)
{
#Write-Output "Office: 2013-32bit" | out-file $PostUp -encoding ascii -Append -Noclobber
2013
}
#check for office 2013 64bit
ElseIf (Test-Path $20133264)
{
#Write-Output "Office: 2013-64bit" | out-file $PostUp -encoding ascii -Append -Noclobber
20133264
}
#check for office 2016 32bit
ElseIf (Test-Path $2016)
{
#Write-Output "Office: 2016-32bit" | out-file $PostUp -encoding ascii -Append -Noclobber
2016
}
#check for office 2016 64bit
ElseIf (Test-Path $20163264)
{
#Write-Output "Office: 2016-64bit" | out-file $PostUp -encoding ascii -Append -Noclobber
20163264
}
Else
{
#Write-Output "No Office Installed" | out-file $PostUp -encoding ascii -Append -Noclobber
$null
}
ExitError: Resource has been moved or is unavailable. Please contact the forum admin.

View File

@@ -1,5 +1,5 @@
$WimFile = "D:\TEMP\Windows10_1703\sources\install.wim" $WimFile = "C:\users\test\Desktop\Windows10\win10-1709\sources\install.wim"
$MountPath = D:\TEMP\Mount $MountPath = C:\users\test\Desktop\Mount
Mount-WindowsImage -ImagePath $WimFile -Index 1 -Path $MountPath Mount-WindowsImage -ImagePath $WimFile -Index 1 -Path $MountPath

View File

@@ -0,0 +1,12 @@
Windows Registry Editor Version 5.00
; Created by: Shawn Brink
; http://www.tenforums.com
; Tutorial: http://www.tenforums.com/tutorials/6942-desktop-icons-add-remove-windows-10-a.html
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel]
"{59031a47-3f72-44a7-89c5-5595fe6b30ee}"=dword:00000000
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu]
"{59031a47-3f72-44a7-89c5-5595fe6b30ee}"=dword:00000000

View File

@@ -1 +1 @@
import-startlayout -layoutpath c:\Windows\Temp\Cleanstartmenu.xml -MountPath $env:SystemDrive\ import-startlayout -layoutpath c:\Windows\Temp\Cleanstartmenu_v1.xml -MountPath $env:SystemDrive\

View File

@@ -0,0 +1,32 @@
<LayoutModificationTemplate xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification" xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" xmlns:taskbar="http://schemas.microsoft.com/Start/2014/TaskbarLayout" Version="1">
<LayoutOptions StartTileGroupCellWidth="6" />
<DefaultLayoutOverride>
<StartLayoutCollection>
<defaultlayout:StartLayout GroupCellWidth="6">
<start:Group Name="Créer">
<start:Tile Size="2x2" Column="0" Row="2" AppUserModelID="microsoft.windowscommunicationsapps_8wekyb3d8bbwe!Microsoft.WindowsLive.Calendar" />
<start:Tile Size="4x2" Column="0" Row="0" AppUserModelID="microsoft.windowscommunicationsapps_8wekyb3d8bbwe!Microsoft.WindowsLive.Mail" />
<start:Tile Size="2x2" Column="4" Row="2" AppUserModelID="Microsoft.Office.OneNote_8wekyb3d8bbwe!microsoft.onenoteim" />
</start:Group>
<start:Group Name="Outils">
<start:Tile Size="1x1" Column="0" Row="0" AppUserModelID="Microsoft.WindowsCalculator_8wekyb3d8bbwe!App" />
</start:Group>
<start:Group Name="Université d'Orléans">
<start:Tile Size="2x2" Column="0" Row="0" AppUserModelID="Microsoft.RemoteDesktop_8wekyb3d8bbwe!App" />
<start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell.lnk" />
</start:Group>
<start:Group Name="Explorer">
<start:Tile Size="2x2" Column="0" Row="0" AppUserModelID="Microsoft.BingWeather_8wekyb3d8bbwe!App" />
</start:Group>
</defaultlayout:StartLayout>
</StartLayoutCollection>
</DefaultLayoutOverride>
<CustomTaskbarLayoutCollection PinListPlacement="Replace">
<defaultlayout:TaskbarLayout>
<taskbar:TaskbarPinList>
<taskbar:DesktopApp DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Accessories\Internet Explorer.lnk"/>
<taskbar:UWA AppUserModelID="Microsoft.Office.Word_8wekyb3d8bbwe!microsoft.word" />
</taskbar:TaskbarPinList>
</defaultlayout:TaskbarLayout>
</CustomTaskbarLayoutCollection>
</LayoutModificationTemplate>

21
Windows10/RemoveApps.xml Normal file
View File

@@ -0,0 +1,21 @@
Microsoft.3DBuilder
Microsoft.Appconnector
Microsoft.BingFinance
Microsoft.BingNews
Microsoft.BingSports
Microsoft.BingWeather
Microsoft.CommsPhone
Microsoft.ConnectivityStore
Microsoft.Getstarted
Microsoft.Messaging
Microsoft.MicrosoftOfficeHub
Microsoft.MicrosoftSolitaireCollection
Microsoft.Office.OneNote
Microsoft.Office.Sway
Microsoft.People
Microsoft.SkypeApp
Microsoft.WindowsAlarms
microsoft.windowscommunicationsapps
Microsoft.XboxApp
Microsoft.ZuneMusic
Microsoft.ZuneVideo

View File

@@ -0,0 +1,3 @@
# Pour ajouter le net Framework 3.5 sur un PC windows 10 en version 1709
# Les sources de l'image sont sur le sccm
DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:d:\sources\sxs

View File

@@ -0,0 +1,9 @@
<CustomTaskbarLayoutCollection PinListPlacement="Replace">
<defaultlayout:TaskbarLayout>
<taskbar:TaskbarPinList>
<taskbar:DesktopApp DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Accessories\Internet Explorer.lnk"/>
<taskbar:DesktopApp DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Accessories\Paint.lnk" />
<taskbar:UWA AppUserModelID="Microsoft.Office.Word_8wekyb3d8bbwe!microsoft.word" />
</taskbar:TaskbarPinList>
</defaultlayout:TaskbarLayout>
</CustomTaskbarLayoutCollection>

View File

@@ -0,0 +1,12 @@
$installedapps = get-AppxPackage
$aumidList = @()
foreach ($app in $installedapps)
{
foreach ($id in (Get-AppxPackageManifest $app).package.applications.application.id)
{
$aumidList += $app.packagefamilyname + "!" + $id
}
}
$aumidList

View File

@@ -0,0 +1,23 @@
history
$PSVersiontable
import-module "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\DISM"
get-module
cd C:\users\andre.lasfargues\Downloads
.\removeapps.ps1 -pathtowim "E:\Logiciel\ISO\win10-1709\sources\install.wim"
$env:Path = ($env:Path + ";C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tool...
.\removeapps.ps1 -pathtowim "E:\Logiciel\ISO\win10-1709\sources\install.wim"
get-module
Remove-AppxProvisionedPackage
.\removeapps.ps1 -pathtowim "E:\Logiciel\ISO\win10-1709\sources\install.wim" -index 2
history
history
cd ..
cd .\AppData\Local\Temp
Remove-Item -help
Remove-Item --
Remove-Item \?
Remove-Item /?
Remove-Item help
get-help Remove-Item
rmdir .\ct4nu02v.coa
rmdir -Recurse -Force .\ct4nu02v.coa

View File

@@ -0,0 +1,36 @@
<LayoutModificationTemplate xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" Version="1" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification">
<LayoutOptions StartTileGroupsColumnCount="2" />
<DefaultLayoutOverride LayoutCustomizationRestrictionType="OnlySpecifiedGroups">
<RequiredStartGroupsCollection>
<RequiredStartGroups>
<AppendGroup Name="Créer">
<start:DesktopApplicationTile DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\CodeBlocks\CodeBlocks.lnk" Size="2x2" Column="0" Row="0" />
<start:DesktopApplicationTile AppUserModelID="{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\FreeMind\FreeMind.exe" Size="2x2" Column="2" Row="0" />
</AppendGroup>
<AppendGroup Name="Outils">
<start:Tile AppUserModelID="Microsoft.WindowsCalculator_8wekyb3d8bbwe!App" Size="1x1" Column="0" Row="0" />
<start:DesktopApplicationTile DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Accessories\Snipping Tool.lnk" Size="1x1" Column="1" Row="0" />
</AppendGroup>
</RequiredStartGroups>
<RequiredStartGroups>
<AppendGroup Name="IUT de RODEZ">
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell.lnk" />
<start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Mozilla Firefox.lnk" />
</AppendGroup>
<AppendGroup Name="Explorer">
<start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\System Tools\File Explorer.lnk" />
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\System Tools\computer.lnk" />
</AppendGroup>
</RequiredStartGroups>
</RequiredStartGroupsCollection>
</DefaultLayoutOverride>
<CustomTaskbarLayoutCollection PinListPlacement="Replace">
<defaultlayout:TaskbarLayout>
<taskbar:TaskbarPinList>
<taskbar:DesktopApp DesktopApplicationID="Microsoft.Windows.Explorer" />
<taskbar:UWA AppUserModelID="TheDocumentFoundation.LibreOffice.Startcenter" />
</taskbar:TaskbarPinList>
</defaultlayout:TaskbarLayout>
</CustomTaskbarLayoutCollection>
<AppendOfficeSuite/>
</LayoutModificationTemplate>

View File

@@ -0,0 +1,29 @@
<LayoutModificationTemplate xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" xmlns:taskbar="http://schemas.microsoft.com/Start/2014/TaskbarLayout" Version="1" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification">
<LayoutOptions StartTileGroupCellWidth="6" />
<DefaultLayoutOverride LayoutCustomizationRestrictionType="OnlySpecifiedGroups">
<StartLayoutCollection>
<defaultlayout:StartLayout GroupCellWidth="6">
<start:Group Name="Outils">
<start:Tile Size="1x1" Column="0" Row="0" AppUserModelID="Microsoft.WindowsCalculator_8wekyb3d8bbwe!App" />
<start:DesktopApplicationTile Size="1x1" Column="1" Row="0" DesktopApplicationID="{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\SnippingTool.exe" />
</start:Group>
<start:Group Name="IUT de RODEZ">
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationID="{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe" />
<start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationID="308046B0AF4A39CB" />
<start:DesktopApplicationTile Size="2x2" Column="4" Row="0" DesktopApplicationID="{6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\EXCEL.EXE" />
<start:DesktopApplicationTile Size="2x2" Column="0" Row="2" DesktopApplicationID="{6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\WINWORD.EXE" />
<start:DesktopApplicationTile Size="2x2" Column="2" Row="2" DesktopApplicationID="Microsoft.Windows.Explorer" />
<start:DesktopApplicationTile Size="2x2" Column="4" Row="2" DesktopApplicationID="Microsoft.Windows.Computer" />
</start:Group>
</defaultlayout:StartLayout>
</StartLayoutCollection>
</DefaultLayoutOverride>
<CustomTaskbarLayoutCollection PinListPlacement="Replace">
<defaultlayout:TaskbarLayout>
<taskbar:TaskbarPinList>
<taskbar:DesktopApp DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Accessories\InternetExplorer.lnk" />
<taskbar:DesktopApp DesktopApplicationID="TheDocumentFoundation.LibreOffice.Startcenter" />
</taskbar:TaskbarPinList>
</defaultlayout:TaskbarLayout>
</CustomTaskbarLayoutCollection>
</LayoutModificationTemplate>

View File

@@ -0,0 +1,3 @@
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsStore /v AutoDownload /t REG_DWORD /d 00000002 /f
reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager /v SilentInstalledAppsEnabled /t REG_DWORD /d 00000000 /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CloudContent /v DisableWindowsConsumerFeatures /t REG_DWORD /d 00000001 /f

View File

@@ -0,0 +1,129 @@
Name AppID
---- -----
Firefox 308046B0AF4A39CB
FileZilla FileZilla.Client.AppID
FusionInventory Agent Status http://localhost:62354/
FusionInventory Website http://www.fusioninventory.org/
Visiter le site Java.com https://java.com/
Obtenir de l'aide https://java.com/help
Kaspersky Endpoint Security 10 for Windows Kaspersky Lab.KAV.Toasts
Module Active Directory pour Windows PowerShell Microsoft.AutoGenerated.{0A4E7D07-C36B-6375-9827-C71748DA44DE}
Git Bash Microsoft.AutoGenerated.{0FDD9C6B-656B-0F1F-AB08-B1CDBB7067B3}
Reconnaissance vocale de Windows Microsoft.AutoGenerated.{119E4E64-B444-B876-1F09-80182D07FD21}
Observateur dévénements Microsoft.AutoGenerated.{245F8F81-DE65-1904-B2D3-1D7B3B99AF6D}
Moniteur de ressources Microsoft.AutoGenerated.{2486123E-0FE5-4788-B86E-2A11B662F89B}
Git CMD Microsoft.AutoGenerated.{29591C0F-7C09-B655-C0EB-8544FCA7D1DE}
Services Microsoft Azure Microsoft.AutoGenerated.{59F91E5D-883E-92E9-24FE-078CC2D11090}
Gestionnaire du cluster de basculement Microsoft.AutoGenerated.{657F6043-CD64-453D-D529-F87551C3F08C}
Analyseur de performances Microsoft.AutoGenerated.{67DEE369-C509-982D-F248-ABCEA8A27352}
DNS Microsoft.AutoGenerated.{9AD5A3A4-1821-C8F2-F6CD-500884B24B63}
Stratégie de sécurité locale Microsoft.AutoGenerated.{9ADB7646-599B-C4DC-3F28-5C1CCE1CEE3C}
Planificateur de tâches Microsoft.AutoGenerated.{AB568050-88B9-C154-AE66-C3E1E4EF4479}
Gestion du système de fichiers distribués DFS Microsoft.AutoGenerated.{AE417AD1-CD50-0121-1BC6-BA9B52CCFE40}
Rechercher les mises à jour Microsoft.AutoGenerated.{B278EA02-0F5D-F836-26F5-C29CC5B94076}
A propos de Java Microsoft.AutoGenerated.{C8FCA9AC-D3BE-FE55-4554-095E959D9E9F}
Gestion de lordinateur Microsoft.AutoGenerated.{E28FB7A9-B922-0A8D-14A7-F4A12E61B8C2}
Gestion des stratégies de groupe Microsoft.AutoGenerated.{E95C5F22-4ED9-EA4D-7C4B-8D83979BA186}
Gestionnaire de ressources du serveur de fichiers Microsoft.AutoGenerated.{ECCA326E-1AD6-9943-97D7-A4FB378E1469}
Gestionnaire des tâches Microsoft.AutoGenerated.{F9BA49F8-6791-D89D-CCEC-71D3D9C0C7AE}
Internet Explorer Microsoft.InternetExplorer.Default
Outlook 2016 Microsoft.Office.OUTLOOK.EXE.16
Centre logiciel Microsoft.SoftwareCenter.DesktopToasts
Ce PC Microsoft.Windows.Computer
Panneau de configuration Microsoft.Windows.ControlPanel
Explorateur de fichiers Microsoft.Windows.Explorer
Connexion Bureau à distance Microsoft.Windows.RemoteDesktop
Exécuter Microsoft.Windows.Shell.RunDialog
Microsoft Edge MSEdge
Préférences linguistiques dOffice 2016 zn=BVz!!!!4!!!!MKKSkSetLanguageFiles<
Centre de téléchargement Office 2016 zn=BVz!!!!4!!!!MKKSkWxpFiles<
LisezMoi \\serapps\Applications\Windesign\LisezMoi.pdf
Administration \\serapps\Applications\Windesign\PROGRAMMES\Admin.exe
Aide Win'Design \\serapps\Applications\Windesign\PROGRAMMES\WinDsign.chm
Win'Design \\serapps\Applications\Windesign\PROGRAMMES\WinDsign.exe
Uninstall Win'Design \\serapps\Applications\Windesign\uninstallWD17.0.exe
Modification ADSI {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\adsiedit.msc
Autorité de certification {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\certsrv.msc
Table des caractères {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\charmap.exe
Nettoyage de disque {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\cleanmgr.exe
Mise à jour adaptée aux clusters {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\ClusterUpdateUI.exe
Invite de commandes {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\cmd.exe
Services de composants {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\comexp.msc
Défragmenter et optimiser les lecteurs {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\dfrgui.exe
DHCP {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\dhcpmgmt.msc
Domaines et approbations Active Directory {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\domain.msc
Utilisateurs et ordinateurs Active Directory {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\dsa.msc
Centre dadministration Active Directory {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\dsac.exe
Sites et services Active Directory {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\dssite.msc
Initiateur iSCSI {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\iscsicpl.exe
Gestionnaire de licences des services Bureau à distance {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\licmgr.exe
Outil de diagnostic des licences des services Bureau à distance {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\lsdiag.msc
Loupe {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\magnify.exe
Diagnostic de mémoire Windows {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\MdSched.exe
Configuration du système {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\msconfig.exe
Informations système {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\msinfo32.exe
Paint {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\mspaint.exe
Narrateur {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\narrator.exe
Gestionnaire déquilibrage de la charge réseau {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\nlbmgr.exe
Bloc-notes {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\notepad.exe
Gestion des répondeurs en ligne {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\ocsp.msc
Sources de données ODBC (64 bits) {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\odbcad32.exe
Clavier visuel {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\osk.exe
Gestion de limpression {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\printmanagement.msc
Enregistreur dactions utilisateur {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\psr.exe
Assistance rapide {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\quickassist.exe
Gestion de laccès à distance {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\RAMgmtUI.exe
Lecteur de récupération {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\RecoveryDrive.exe
Routage et accès distant {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\rrasmgmt.msc
Gestionnaire de serveur {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\ServerManager.exe
Services {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\services.msc
Assistant Fichier de données de protection {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\ShieldingDataFileWizard.exe
Outil Capture décran {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\SnippingTool.exe
Assistant de disque de modèle {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\TemplateDiskWizard.exe
Gestionnaire de passerelle Bureau à distance {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\tsgateway.msc
Outils dactivation en volume {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\vmw.exe
Pare-feu Windows Defender avec fonctions avancées de sécurité {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WF.msc
Télécopie et numérisation Windows {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WFS.exe
Windows PowerShell {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe
Windows PowerShell ISE {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\PowerShell_ISE.exe
7-Zip Help {6D809377-6AF0-444B-8957-A3773F02200E}\7-Zip\7-zip.chm
7-Zip File Manager {6D809377-6AF0-444B-8957-A3773F02200E}\7-Zip\7zFM.exe
Panneau de saisie mathématique {6D809377-6AF0-444B-8957-A3773F02200E}\Common Files\Microsoft Shared\Ink\mip.exe
Uninstall {6D809377-6AF0-444B-8957-A3773F02200E}\FileZilla FTP Client\uninstall.exe
gitg {6D809377-6AF0-444B-8957-A3773F02200E}\gitg\bin\gitg.exe
Git GUI {6D809377-6AF0-444B-8957-A3773F02200E}\Git\cmd\git-gui.exe
Configurer Java {6D809377-6AF0-444B-8957-A3773F02200E}\Java\jre1.8.0_211\bin\javacpl.exe
IntelliJ IDEA 2019.1.2 {6D809377-6AF0-444B-8957-A3773F02200E}\JetBrains\IntelliJ IDEA 2019.1.2\bin\idea64.exe
IntelliJ IDEA Community Edition 2019.1.2 {6D809377-6AF0-444B-8957-A3773F02200E}\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\bin\idea64.exe
Excel 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\EXCEL.EXE
Access 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\MSACCESS.EXE
Journal de télémétrie pour Office 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\msoev.exe
Tableau de bord de télémétrie pour Office 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\msotd.exe
Publisher 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\MSPUB.EXE
OneNote 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\ONENOTE.EXE
PowerPoint 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\POWERPNT.EXE
Visio 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\VISIO.EXE
Project 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\WINPROJ.EXE
Word 2016 {6D809377-6AF0-444B-8957-A3773F02200E}\Microsoft Office\Office16\WINWORD.EXE
SumatraPDF {6D809377-6AF0-444B-8957-A3773F02200E}\SumatraPDF\SumatraPDF.exe
Services WSUS (Windows Server Update Services) {6D809377-6AF0-444B-8957-A3773F02200E}\Update Services\AdministrationSnapin\wsus.msc
WordPad {6D809377-6AF0-444B-8957-A3773F02200E}\Windows NT\Accessories\wordpad.exe
Acrobat Reader DC {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe
SAP Logon {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\SAP\FrontEnd\SAPgui\saplogon.exe
SAP GUI Configuration {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\SAP\FrontEnd\SAPgui\sapsettingsshow.exe
Pageant {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\x2goclient\pageant.exe
PuTTYgen {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\x2goclient\puttygen.exe
X2Go Client {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}\x2goclient\x2goclient.exe
Sources de données ODBC (32 bits) {D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}\odbcad32.exe
Windows PowerShell (x86) {D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}\WindowsPowerShell\v1.0\powershell.exe
Windows PowerShell ISE (x86) {D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}\WindowsPowerShell\v1.0\PowerShell_ISE.exe
Centre de sécurité Windows Defender Microsoft.Windows.SecHealthUI_cw5n1h2txyewy!SecHealthUI
Paramètres windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel
Caméra Microsoft.WindowsCamera_8wekyb3d8bbwe!App
Calculatrice Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
Photos Microsoft.Windows.Photos_8wekyb3d8bbwe!App
Éditeur de vidéo Microsoft.Windows.Photos_8wekyb3d8bbwe!SecondaryEntry
Courrier microsoft.windowscommunicationsapps_8wekyb3d8bbwe!microsoft.windowslive.mail
Calendrier microsoft.windowscommunicationsapps_8wekyb3d8bbwe!microsoft.windowslive.calendar
Microsoft Store Microsoft.WindowsStore_8wekyb3d8bbwe!App
Cortana Microsoft.Windows.Cortana_cw5n1h2txyewy!CortanaUI

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<settings pass="specialize">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CopyProfile>true</CopyProfile>
</component>
</settings>
</unattend>

View File

@@ -0,0 +1,46 @@
# =====================================================================
#
# création d'un tableau contenant les noms des Apps à desinstaller,
# puis utilisation de -In $Packages ou foreach ($package in $packages) { Get-AppxPackage | where Name -like *$Packages* | remove...etc}
# cela permet de donner des nom incomplets, s'ils changent...
#
# =====================================================================
# List of applications to remove
$Packages =
'Microsoft.3DBuilder',
'Microsoft.BingFinance',
'Microsoft.BingNews',
'Microsoft.BingSports',
'Microsoft.BingWeather',
'Microsoft.CommsPhone',
'Microsoft.ConnectivityStore',
'Microsoft.Getstarted',
'Microsoft.Messaging',
'Microsoft.MicrosoftOfficeHub',
'Microsoft.MicrosoftSolitaireCollection',
'Microsoft.Office.OneNote',
'Microsoft.Office.Sway',
'Microsoft.People',
'Microsoft.SkypeApp',
'Microsoft.XboxApp',
'Microsoft.ZuneMusic',
'Microsoft.ZuneVideo',
'Microsoft.WindowsMaps',
'Microsoft.Windows.SecondaryTileExperience',
'Microsoft.Windows.ContentDeliveryManager',
'Microsoft.Windows.CloudExperienceHost',
'Microsoft.Advertising.Xaml',
'9E2F88E3.Twitter',
'king.com.CandyCrushSodaSaga',
'Windows.MiracastView',
'Microsoft.Windows.ParentalControls',
'Microsoft.MicrosoftSolitaireCollection',
'WindowsFeedback'
# remove installed appx for current user
Get-AppxPackage | Where-Object Name -In $Packages | Remove-AppxPackage | Out-Null
# remove all installed appx for all users
Get-AppxPackage -AllUser | Where-Object Name -In $Packages | Remove-AppxPackage | Out-Null
# remove provisioned appx
Get-AppxProvisionedPackage -Online | Where-Object DisplayName -In $Packages | Remove-ProvisionedAppxPackage -Online | Out-Null

View File

@@ -0,0 +1,12 @@
1 get-smbServerConfiguration
2 Get-NetFirewallRule
3 Get-NetFirewallRule -DisplayName "Gestion à distance du Pare-feu Windows (RPC)"
4 Set-NetFirewallRule -DisplayName "Gestion à distance du Pare-feu Windows (RPC)" -Enabled True
5 Set-NetFirewallRule -DisplayName "Gestion à distance du Pare-feu Windows (RPC-EPMAP)" -Enabled True
6 Get-NetFirewallRule -DisplayName "Gestion à distance du Pare-feu Windows (RPC)"
7 regedit
8 Get-Module
9 Get-Module -ListAvailable
10 import-module ServerManager -PassThru
11 Get-Command -Module servermanager
12 Get-ChildItem -Recurse -Path "C:\Program Files" -Include "7*.exe"| Where-Object {!$_.PSIsContainer}

View File

@@ -0,0 +1,18 @@
function global:Prompt {
## Get the last item from the history
$historyItem = Get-History -Count 1
## If there were any history items
if($historyItem)
{
# Save previous command details in this directory AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline
$historyItem| convert-to-tsv | select -skip 1 >> ".command-history.txt"
}
}
function global:convert-to-csv {
$input |
ConvertTo-Csv -delimiter " " -NoTypeInformation |
# First replace: Remove double-quotes 1) at beginning of line 2) at end of line 3) before a tab using regex look-ahead 4) after a tab using regex look-behind
# Second replace: Replace 2 double-quotes with one (added by convert-to-csv)
% { -replace '^"|"$|"(?=\t)|(?<=\t)"', '' -replace '""','"' }
}

View File

@@ -0,0 +1,11 @@
New-PSDrive -Name P -Root \\sernasetu.iut.local\Admin -PSProvider FileSystem -Persist -Credential administrateur@iut.local
cd .\Desktop\
.\makecert.exe -pe -n "CN=RootCA4" -ss root -sr LocalMachine -sky signature -r "RootCA4.cer"
.\makecert.exe -pe -n "CN=hyper2.iut.rdz" -ss my -sr LocalMachine -sky exchange -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 -in "RootCA4" -is root -ir LocalMachine -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 hyper2.cer
certutil.exe -addstore -f Root "RootCA.cer"
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Replication" /v DisableCertRevocationCheck /d 1 /t REG_DWORD /f
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
Get-netadapter
winrm quickconfig
Enable-PSRemoting -force
winrm s winrm/config/client '@{TrustedHosts="hyper1.iut.rdz"}'

1
id_rsa_foret.pub Normal file
View File

@@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC4KLy5dX2bq9uc6lyzbYsA1I3EBvgC7Uhq1dh3EVo1kCepiZdl08Uh7mj+mHfA/57jzSrQ+3sv7ijNi26/FChpEVAsFmOuTumBhUiDOJ8EMloMxf+C/8tiv98JBxf8vu8e21TFFn575gkXjbMweyX/ywjDo4a1TWR1mdFMGLwF5v32LYLNeyEeGIVfRQlo3LfzRzz3ZRkajQ5cfsi2EihCxQgi5E7z55KcJl3TEI4PeYUCGDf9PRBxN+OPRWUypWL23/IgFNXgOANmQJu5naIGu/jjHhBuLTs7WWm1gu3OE13Z/2krK0NzkoczJIrM+//lFEdhuT7D5kHxdlVHarZnQe2AB72dKT7gKlMgprqE+SQjdMucq3Pe6vWMzJ7O8nr82g/5nLje7r8zmIp9CEDO5w+g4DMQElqqc7pPpiJB9eUkQiNXB29xglWJTET6BnzvEWsUN0mENNXSLekip5P5ue/zI797tqULQP2j6/tLPfrIznxnt6C3jGpp3p/iB5pMqd61pfRFC2MFqsQDJudn7zJnBthzlUgyPXah8Ydn2TiFMl8DH6Ib+hziAoPbVn4wzVTTBCphpVbhqI8jksAWrl2pDk6G1xpEZUTp2vOWm4kb87ACGh3zGouevD4jWmTmHUSnI5cmj805s/lEoImU5BP3GqP62QLxMlW5w/lsbQ== andre@foret

View File

@@ -0,0 +1,491 @@
# =======================================================
# Fonction qui ecrit les messages sur la sortie standard
# Usage : Write-OutputConsole ($theme)
# =======================================================
function Write-OutputConsole($theme) {
if ( $theme -eq "lancement") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde en local de Vos Documents et de Votre Bureau est en cours. !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "lancementvol") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde sur Serveur distant de Vos Documents et de Votre Bureau !"
Write-Output "! est en cours. !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "zipprob") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La compression de la messagerie a echoué !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "nospace") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Disque dur C Local n'a pas assez d'espace Libre !"
Write-Output "! !"
Write-Output "! La sauvegarde est annulée !"
Write-Output "! Contactez votre administrateur. !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "novoltaire") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Serveur de Sauvegarde est indiponible !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! La Sauvegarde distante est Annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagloc") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Locale de Vos Documents e tde Votre Bureau a déjà été lancée !"
Write-Output "! !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagnet") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Réseau de Vos Documents et de Votre Bureau !"
Write-Output "! a déjà été lancée !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
}
# =======================================================
# Fonction qui envoie un email avec 2 attachements
# =======================================================
function Send-EMail($argFrom, $argTo, $argtoCC, $argPriority, $argSubject, $argBody, $argAtt, $argSmtp) {
$mail = New-Object System.Net.Mail.MailMessage
$smtpClient = new-object system.net.mail.SmtpClient($argSmtp)
$mail.Body = $argBody
$mail.Subject = $argSubject
$mail.priority = $argPriority
$mail.From = $argFrom
$mail.To.Add($argTo)
if ($argtoCC) {
$mail.CC.Add($argtoCC)
}
if (!($argAtt -eq $null)) {
$att = new-object Net.Mail.Attachment $argAtt
$mail.Attachments.Add($att)
}
$smtpClient.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$smtpClient.Send($mail)
$mail.Attachments.Dispose()
$mail = $null
$smtpClient = $null
}
# =======================================================================
# Fonction qui affiche une boite de dialogue qui se ferme automatiquement
# =======================================================================
function DisplayMessageBox($argText, $argDelayDisplay, $argTitre, $argButton) {
$job=Start-Job -ArgumentList $argText,$argDelayDisplay,$argTitre,$argButton -ScriptBlock {
$a = new-object -comobject wscript.shell
$a.popup($args[0],$args[1],$args[2],$args[3])
}
return $job;
}
# =================================================================================================
# DESCRIPTION: Displays the attention message box & checks to see if the user clicks the ok button.
# Affiche une boîte de dialogue fenêtrée
# Prérequis [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# =================================================================================================
function Show-MessageBox([string] $Message,[string] $Titre="Attention !!", [String] $IconType="Warning",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
function Show-QuestionBox([string] $Message,[string] $Titre="Question ??", [String] $IconType="Question",[String] $BtnType="YesNo") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre,[Windows.Forms.MessageBoxButtons]::$BtnType, [Windows.Forms.MessageBoxIcon]::$IconType)
}
function Show-InfoBox([string] $Message,[string] $Titre="Pour votre Information !!", [String] $IconType="Information",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
# =================================================
# Renvoi la Taille d'un repertoire en octets
# =================================================
function Get-FolderSize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
# =================================================
# Renvoi la Taille d'un fichier en octet
# =================================================
function Get-FileSize($Path) {
# On verifie si le path exist
if(test-path $Path){
$colItems = (Get-ChildItem $Path)
return $colItems.Length
}
else {
return 0
}
}
# ==================================================
# Renvoie la Taille d'un fichier en Go
# ==================================================
function Get-FileSizeGB($Path){
return ("{0:N2}" -f ((Get-FileSize $Path) /1GB))
}
# ===========================================================
# Nettoyage des Logs
# ===========================================================
function Delete-Logs($argDirectoryLogs,$argDelay){
$jour = [DateTime]::Today
$lastMod = $jour.AddDays(-$argDelay)
#Récupere la liste des fichiers logs antérieurs à la date
$Files = get-childitem $argDirectoryLogs -include *.log -recurse | Where {$_.LastWriteTime -le "$lastMod"}
if (!($Files -eq $null)) {
foreach ($File in $Files) {
write-host $File
Remove-Item $File
}
}
}
# =========================================================================
# Fonction de récupération du mail utilisateur dans le fichier sur Voltaire
# =========================================================================
function Get-Email {
param ([string]$login,[string]$filelogs)
Get-Content $filelogs | Where-Object { $_.split(";")[0] -match "$login"} | foreach {$_ -replace "^$login;", ""}
}
# =======================================================
# Fonction qui initialise le bon path de la messagerie
# =======================================================
function Find-DirectoryMessagerie {
param ([string]$pathDocsUserLocation)
Set-Location $pathDocsUserLocation
Get-ChildItem "./" | Where-Object {$_.Attributes -eq "Directory"} | Where-Object {$_.Name -match "^[M-m]essagerie$"} | foreach {$_.FullName}
}
# =========================================================================
# Fonctions relatives à la taille du disque C
# =========================================================================
function Get-FreeSpaceCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace/1GB,2)}
}
function Get-FreeSpaceC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
}
function Get-SizeC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
}
function Get-SizeCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size/1GB,2)}
}
function espacedispo
{
$freespaceC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
$sizeC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
$freespaceCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace / 1073741824,2)}
$sizeCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size / 1073741824,2)}
$docspace = (Get-FolderSize $DocsUserLocation).Sum
$burspace = (Get-FolderSize $BureauUserLocation).Sum
$totaltoback = $burspace + $docspace
$docspaceGB = [Math]::round($docspace/1GB,2)
$totaltobackGB = [Math]::round($totaltoback/1GB,2)
$spaceminfree = $totaltoback + 21474836480
echo $spaceminfree
echo $freespaceCGB
if
( $freespaceC -lt $spaceminfree )
{
$greenflag = 1
}
else
{
$greenflag = 0
}
return $greenflag
}
function Kill-Process ($app) {
if (Get-Process $app -ErrorAction silentlycontinue) {
Get-Process $app | Stop-Process
Start-Sleep -s 2
}
}
function Get-OS {
return (Get-WmiObject -class Win32_OperatingSystem).Caption | foreach {$_ -replace " ", ""}
}
#=======================================================
# Fonction qui défini laptop ou desktop
# =======================================================
function Get-PCtype {
return (Get-WmiObject -class Win32_computersystem).PCSystemType }
$pctype = Get-PCtype
if ($pctype -ne "2")
{$fixe = "Oui"}
else
{$fixe = "Non"}
# =======================================================
# Fonction qui écrit des indicateurs dans un fichier
# =======================================================
function Set-Indicator($fichier) {
#Si le fichier n'existe pas, je crée un nouveau fichier.
if ((Test-Path $fichier) -ne "True") { New-Item -ItemType file -Path $indicateurs -Force }
# Ajoute une ligne dans le fichier.
# Les champs sont l'utilisateur, l'ordinateur, les 5 codes de sortie des commandes robocopy, les dates de debut et de fin, la taille en GB à copier à distance
# et l'espace libre suffisant Oui ou Non
Add-Content -Path $fichier -Value "$UserName;$ComputerName;$DocExitCode;$BurExitCode;$BurVolExitCode;$DocVolExitCode;$Tstart;$Tend;$sizetobackGB;$nospace"
}
# =======================================================
# Déclaration des variables globales
# =======================================================
# Portable ou Fixe
#$fixe = "Oui"
# Serveur de backup
$BackupServer = "CLUSTER_SYNOLOG"
# Serveur de Backup FQDN
$BackupServerfdqn = "CLUSTER_SYNOLOG.iut.local"
# Répertoire partagé sur le serveur
$ShareBackupServer = "Personnel\MonDossier"
# Nom de l'ordinateur
$ComputerName = $Env:COMPUTERNAME
# Nom de la session
$UserName = Enjalbert.S
# Initialisation du jour de la semaine
$numjour = Get-Date -UFormat %u
# Initialisation du Jour de l'année
$dayofyear = (get-date).dayofyear
# Répertoire de sauvegarde sur le serveur aubrac
$DirBackVol = "\\$BackupServerfdqn\$ShareBackupServer\$UserName"
# Nom du repertoire de logs
$NameDirectoryLogs = "logssauv"
# Nom du repertoire de logs Local
$NameDirectoryLogsLocal = "localogssauv"
# Nom du serveur smtp
$SmtpServerName = "relay.iut-rodez.fr"
# Mail du support
$toSupport = "support@iut-rodez.fr"
# Emplacement du fichier de correspondance des emails (attention à ce qu'il ne soit pas modifié par des utilisateurs!)
$filelogins = "\\$BackupServerfdqn\$ShareBackupServer\logssauv\login-email.csv"
# Champ FROM des courriel
if ((Test-Path $filelogins) -ne "True") {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
$mailfrom = Get-EMail $UserName $filelogins
}
}
if ((Test-Path $filelogins) -ne "True") {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
$Toclient = Get-EMail $UserName $filelogins
}
}
# Fichier des indicateurs sur Cluster_synolog
$indicateurs = "\\$BackupServerfdqn\$ShareBackupServer\logssauv\indicateurs$dayofyear.txt"
# Localisation du profil des utilisateurs (XP ou seven)
$ProfileUserLocation = $Env:UserProfile
$DirectoryBackup = "$ProfileUserLocation\Copie-Y"
$NameDirectoryLogsVol = "$DirectoryBackup\Logssauv"
$fichierflagnet = "$DirectoryBackup\flag-net.txt"
$os = Get-OS
#Liste des fichiers à exclure
$FileExclude = "`"*.ogg`" `"*.flac`" `"*.mp3`" `"*.wav`" `"*.wma`" `"*.aac`" `"*.mpeg`" `"*.ogm`" `"*.avi`" `"*.flv`" `"*.wmv`" `"*.mov`" `"*.divx`" `"*.xvid`" "
# Nom du fichier logs
$NameDocVolLogs = "SavDocVol"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$DelayRetentionLogs = 8
$listJob = @()
$ExitCode = @{
"16"="Erreur fatale lors de l'opération. Voir fichier de Log"
"15"="Echec de la copie. Voir le fichier de Log."
"14"="Echec de la copie. Voir le fichier de Log."
"13"="Echec de la copie. Voir le fichier de Log."
"12"="Echec de la copie. Voir le fichier de Log."
"11"="Echec de la copie. Voir le fichier de Log."
"10"="Echec de la copie. Voir le fichier de Log."
"9"="Echec de la copie. Voir le fichier de Log."
"8"="Echec de la copie. Plisieurs fichiers n'ont pas été copiés. Voir le fichier de Log."
"7"="Copie OK. Certains fichiers présents et supplémentaires on généré une incohérence entre la source et la destination. Voir le fichier de Log."
"6"="Copie OK. Certains fichiers et dossiers suplémentaires ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"5"="Copie OK. Certains fichiers ont été copiés et d'autres ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"4"="Copie OK. Une incohérence entre la source et la destination de la sauvegarde a été détectée. Voir le fichier de Log."
"3"="Copie OK. Certains fichiers supplémentaires ont été copiés avec succès."
"2"="Copie OK. Certains fichiers ou répertoires supplémentaires ont été détectés et copiés avec succès."
"1"="Copie OK. Un ou plusieurs fichiers ont été copiés avec succès du répertoire source au répertoire de destination."
"0"="Copie OK. Aucun changement. Le répertoire source était identique au répertoire de destination."
}
$mail = New-Object System.Net.Mail.MailMessage
$killappli = @("outlook","excel","winword","powerpnt","msaccess","mspub","visio","thunderbird","soffice.bin")
$SavDocVolLog = "$NameDirectoryLogsVol\$NameDocVolLogs"
$resultatcopieloc = 0
$resultatcopienet = 0
$pasnecessaireloc = 0
$pasnecessairenet = 0
# FIN VARIABLES GLOBALES DEF ET INIT
# =============================
# DEBUT DU PROGRAMME PRINCIPAL
# =============================
# Chargement d'une librairie pour l'affichade de fenetre
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# On tue les appli genantes
foreach ($i in $killappli){
Kill-Process ($i)
}
Start-Sleep -s 2
# Détermination de l'endroit ou effectuer la sauvegarde
# et la validation ou non de la sauvegarde précédente en local
If (!(Test-Path "$NameDirectoryLogsVol")){
Set-Location "$DirectoryBackup"
New-Item -ItemType Directory -Name "$NameDirectoryLogs"
}
$TimesStart = Get-date -Format 'dddd dd MMM yyyy'
$HourStart = Get-Date -Format 'HH"h"mm'
$Tstart = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# SEQUENCE : COPIE RESEAU
## ================================================================
Write-OutputConsole("lancement")
Start-Sleep -s 2
# Test de la disponibilité du serveur, on arrête le programme si le serveur est injoignable
if ((!(Test-Connection -computer $BackupServer -Count 3 -quiet)) -or (!(Test-Connection -computer $BackupServerfdqn -Count 5 -quiet))) {
Write-OutputConsole("nosynolog")
Show-MessageBox ("Attention !!", "Le serveur de backup n'est pas joignable, la sauvegarde est annulée`nContactez votre administrateur.`n`nCliquez su OK pour Eteindre")
exit
}
# Lancement de la copie Y CLUSTER_SYNOLOG vers Dossier Copie-Y sur Portable
robocopy "$DirBackVol" "$DirectoryBackup" /MIR /R:3 /W:5 /XD $DirectoryExclude >> $SavDocVolLog
$DocVolExitCode = $LASTEXITCODE
if ($DocVolExitCode -lt 8){
# La sauvegarde Locale est réussie, on remet le fichier flag puis on compresse le tout dans le dossier du jour
set-content -path "$fichierflagnet" -value "OK"
$resultatcopienet = 1
}
$TimesEnd = Get-date -Format 'dddd dd MMM yyyy'
$HourEnd = Get-Date -Format 'HH"h"mm'
$Tend = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# 3EME SEQUENCE : INDICATEURS/NOTIFICATIONS
# ================================================================
Delete-Logs $NameDirectoryLogsVol 8
if ($resultatcopienet -eq 1) {
$messagecourriel = "Résultat de la sauvegarde : OK (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Si la sauvegarde a déja été exécutée dans les 18h, elle n'est pas relancée."
$toSupport = $null
}
else {
$messagecourriel = "Un problème est survenu dans l'exécution de votre sauvegarde (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Un problème est survenu dans l'exécution de la sauvegarde pour $UserName. survenu lors de la sauvegarde de Copie-Y démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd.`n`nLes résultats de sauvegardes ont été les suivants :`n`nCopie-Y vers CLUSTER_SYNOLOG `n"+$ExitCode["$DocVolExitCode"]+"`n`Pour de plus amples détails, consultez le fichier log en pièce jointe."
}
If (!(Test-Path "$SavDocVolLog")){
$SavDocVolLog = $null
}
# Message aux utilisateurs
Send-Email $mailfrom $Toclient $toSupport 'High' $messagecourriel $body $SavDocVolLog $SmtpServerName
# TODO:verifier le lancement de la commande mail
# INDICATEURS :
# ------------
#
Set-indicator($indicateurs)
}
{
Exit
}

View File

@@ -0,0 +1,491 @@
# =======================================================
# Fonction qui ecrit les messages sur la sortie standard
# Usage : Write-OutputConsole ($theme)
# =======================================================
function Write-OutputConsole($theme) {
if ( $theme -eq "lancement") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde en local de Vos Documents et de Votre Bureau est en cours. !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "lancementvol") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde sur Serveur distant de Vos Documents et de Votre Bureau !"
Write-Output "! est en cours. !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "zipprob") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La compression de la messagerie a echoué !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "nospace") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Disque dur C Local n'a pas assez d'espace Libre !"
Write-Output "! !"
Write-Output "! La sauvegarde est annulée !"
Write-Output "! Contactez votre administrateur. !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "novoltaire") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Serveur de Sauvegarde est indiponible !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! La Sauvegarde distante est Annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagloc") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Locale de Vos Documents e tde Votre Bureau a déjà été lancée !"
Write-Output "! !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagnet") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Réseau de Vos Documents et de Votre Bureau !"
Write-Output "! a déjà été lancée !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
}
# =======================================================
# Fonction qui envoie un email avec 2 attachements
# =======================================================
function Send-EMail($argFrom, $argTo, $argtoCC, $argPriority, $argSubject, $argBody, $argAtt, $argSmtp) {
$mail = New-Object System.Net.Mail.MailMessage
$smtpClient = new-object system.net.mail.SmtpClient($argSmtp)
$mail.Body = $argBody
$mail.Subject = $argSubject
$mail.priority = $argPriority
$mail.From = $argFrom
$mail.To.Add($argTo)
if ($argtoCC) {
$mail.CC.Add($argtoCC)
}
if (!($argAtt -eq $null)) {
$att = new-object Net.Mail.Attachment $argAtt
$mail.Attachments.Add($att)
}
$smtpClient.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$smtpClient.Send($mail)
$mail.Attachments.Dispose()
$mail = $null
$smtpClient = $null
}
# =======================================================================
# Fonction qui affiche une boite de dialogue qui se ferme automatiquement
# =======================================================================
function DisplayMessageBox($argText, $argDelayDisplay, $argTitre, $argButton) {
$job=Start-Job -ArgumentList $argText,$argDelayDisplay,$argTitre,$argButton -ScriptBlock {
$a = new-object -comobject wscript.shell
$a.popup($args[0],$args[1],$args[2],$args[3])
}
return $job;
}
# =================================================================================================
# DESCRIPTION: Displays the attention message box & checks to see if the user clicks the ok button.
# Affiche une boîte de dialogue fenêtrée
# Prérequis [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# =================================================================================================
function Show-MessageBox([string] $Message,[string] $Titre="Attention !!", [String] $IconType="Warning",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
function Show-QuestionBox([string] $Message,[string] $Titre="Question ??", [String] $IconType="Question",[String] $BtnType="YesNo") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre,[Windows.Forms.MessageBoxButtons]::$BtnType, [Windows.Forms.MessageBoxIcon]::$IconType)
}
function Show-InfoBox([string] $Message,[string] $Titre="Pour votre Information !!", [String] $IconType="Information",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
# =================================================
# Renvoi la Taille d'un repertoire en octets
# =================================================
function Get-FolderSize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
# =================================================
# Renvoi la Taille d'un fichier en octet
# =================================================
function Get-FileSize($Path) {
# On verifie si le path exist
if(test-path $Path){
$colItems = (Get-ChildItem $Path)
return $colItems.Length
}
else {
return 0
}
}
# ==================================================
# Renvoie la Taille d'un fichier en Go
# ==================================================
function Get-FileSizeGB($Path){
return ("{0:N2}" -f ((Get-FileSize $Path) /1GB))
}
# ===========================================================
# Nettoyage des Logs
# ===========================================================
function Delete-Logs($argDirectoryLogs,$argDelay){
$jour = [DateTime]::Today
$lastMod = $jour.AddDays(-$argDelay)
#Récupere la liste des fichiers logs antérieurs à la date
$Files = get-childitem $argDirectoryLogs -include *.log -recurse | Where {$_.LastWriteTime -le "$lastMod"}
if (!($Files -eq $null)) {
foreach ($File in $Files) {
write-host $File
Remove-Item $File
}
}
}
# =========================================================================
# Fonction de récupération du mail utilisateur dans le fichier sur Voltaire
# =========================================================================
function Get-Email {
param ([string]$login,[string]$filelogs)
Get-Content $filelogs | Where-Object { $_.split(";")[0] -match "$login"} | foreach {$_ -replace "^$login;", ""}
}
# =======================================================
# Fonction qui initialise le bon path de la messagerie
# =======================================================
function Find-DirectoryMessagerie {
param ([string]$pathDocsUserLocation)
Set-Location $pathDocsUserLocation
Get-ChildItem "./" | Where-Object {$_.Attributes -eq "Directory"} | Where-Object {$_.Name -match "^[M-m]essagerie$"} | foreach {$_.FullName}
}
# =========================================================================
# Fonctions relatives à la taille du disque C
# =========================================================================
function Get-FreeSpaceCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace/1GB,2)}
}
function Get-FreeSpaceC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
}
function Get-SizeC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
}
function Get-SizeCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size/1GB,2)}
}
function espacedispo
{
$freespaceC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
$sizeC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
$freespaceCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace / 1073741824,2)}
$sizeCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size / 1073741824,2)}
$docspace = (Get-FolderSize $DocsUserLocation).Sum
$burspace = (Get-FolderSize $BureauUserLocation).Sum
$totaltoback = $burspace + $docspace
$docspaceGB = [Math]::round($docspace/1GB,2)
$totaltobackGB = [Math]::round($totaltoback/1GB,2)
$spaceminfree = $totaltoback + 21474836480
echo $spaceminfree
echo $freespaceCGB
if
( $freespaceC -lt $spaceminfree )
{
$greenflag = 1
}
else
{
$greenflag = 0
}
return $greenflag
}
function Kill-Process ($app) {
if (Get-Process $app -ErrorAction silentlycontinue) {
Get-Process $app | Stop-Process
Start-Sleep -s 2
}
}
function Get-OS {
return (Get-WmiObject -class Win32_OperatingSystem).Caption | foreach {$_ -replace " ", ""}
}
#=======================================================
# Fonction qui défini laptop ou desktop
# =======================================================
function Get-PCtype {
return (Get-WmiObject -class Win32_computersystem).PCSystemType }
$pctype = Get-PCtype
if ($pctype -ne "2")
{$fixe = "Oui"}
else
{$fixe = "Non"}
# =======================================================
# Fonction qui écrit des indicateurs dans un fichier
# =======================================================
function Set-Indicator($fichier) {
#Si le fichier n'existe pas, je crée un nouveau fichier.
if ((Test-Path $fichier) -ne "True") { New-Item -ItemType file -Path $indicateurs -Force }
# Ajoute une ligne dans le fichier.
# Les champs sont l'utilisateur, l'ordinateur, les 5 codes de sortie des commandes robocopy, les dates de debut et de fin, la taille en GB à copier à distance
# et l'espace libre suffisant Oui ou Non
Add-Content -Path $fichier -Value "$UserName;$ComputerName;$DocExitCode;$BurExitCode;$BurVolExitCode;$DocVolExitCode;$Tstart;$Tend;$sizetobackGB;$nospace"
}
# =======================================================
# Déclaration des variables globales
# =======================================================
# Portable ou Fixe
#$fixe = "Oui"
# Serveur de backup
$BackupServer = "CLUSTER_SYNOLOG"
# Serveur de Backup FQDN
$BackupServerfdqn = "CLUSTER_SYNOLOG.iut.local"
# Répertoire partagé sur le serveur
$ShareBackupServer = "Personnel\MonDossier"
# Nom de l'ordinateur
$ComputerName = $Env:COMPUTERNAME
# Nom de la session
$UserName = Enjalbert.S
# Initialisation du jour de la semaine
$numjour = Get-Date -UFormat %u
# Initialisation du Jour de l'année
$dayofyear = (get-date).dayofyear
# Répertoire de sauvegarde sur le serveur aubrac
$DirBackVol = "\\$BackupServerfdqn\$ShareBackupServer\$UserName"
# Nom du repertoire de logs
$NameDirectoryLogs = "logssauv"
# Nom du repertoire de logs Local
$NameDirectoryLogsLocal = "localogssauv"
# Nom du serveur smtp
$SmtpServerName = "relay.iut-rodez.fr"
# Mail du support
$toSupport = "support@iut-rodez.fr"
# Emplacement du fichier de correspondance des emails (attention à ce qu'il ne soit pas modifié par des utilisateurs!)
$filelogins = "\\$BackupServerfdqn\$ShareBackupServer\logssauv\login-email.csv"
# Champ FROM des courriel
if ((Test-Path $filelogins) -ne "True") {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
$mailfrom = Get-EMail $UserName $filelogins
}
}
if ((Test-Path $filelogins) -ne "True") {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
$Toclient = Get-EMail $UserName $filelogins
}
}
# Fichier des indicateurs sur \\voltaire\sauvegarde\
$indicateurs = "\\$BackupServerfdqn\$ShareBackupServer\logssauv\indicateurs$dayofyear.txt"
# Localisation du profil des utilisateurs (XP ou seven)
$ProfileUserLocation = $Env:UserProfile
$DirectoryBackup = "$ProfileUserLocation\Copie-Y"
$NameDirectoryLogsVol = "$DirectoryBackup\Logssauv"
$fichierflagnet = "$DirectoryBackup\flag-net.txt"
$os = Get-OS
#Liste des fichiers à exclure
$FileExclude = "`"*.ogg`" `"*.flac`" `"*.mp3`" `"*.wav`" `"*.wma`" `"*.aac`" `"*.mpeg`" `"*.ogm`" `"*.avi`" `"*.flv`" `"*.wmv`" `"*.mov`" `"*.divx`" `"*.xvid`" "
# Nom du fichier logs
$NameDocVolLogs = "SavDocVol"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$DelayRetentionLogs = 8
$listJob = @()
$ExitCode = @{
"16"="Erreur fatale lors de l'opération. Voir fichier de Log"
"15"="Echec de la copie. Voir le fichier de Log."
"14"="Echec de la copie. Voir le fichier de Log."
"13"="Echec de la copie. Voir le fichier de Log."
"12"="Echec de la copie. Voir le fichier de Log."
"11"="Echec de la copie. Voir le fichier de Log."
"10"="Echec de la copie. Voir le fichier de Log."
"9"="Echec de la copie. Voir le fichier de Log."
"8"="Echec de la copie. Plisieurs fichiers n'ont pas été copiés. Voir le fichier de Log."
"7"="Copie OK. Certains fichiers présents et supplémentaires on généré une incohérence entre la source et la destination. Voir le fichier de Log."
"6"="Copie OK. Certains fichiers et dossiers suplémentaires ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"5"="Copie OK. Certains fichiers ont été copiés et d'autres ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"4"="Copie OK. Une incohérence entre la source et la destination de la sauvegarde a été détectée. Voir le fichier de Log."
"3"="Copie OK. Certains fichiers supplémentaires ont été copiés avec succès."
"2"="Copie OK. Certains fichiers ou répertoires supplémentaires ont été détectés et copiés avec succès."
"1"="Copie OK. Un ou plusieurs fichiers ont été copiés avec succès du répertoire source au répertoire de destination."
"0"="Copie OK. Aucun changement. Le répertoire source était identique au répertoire de destination."
}
$mail = New-Object System.Net.Mail.MailMessage
$killappli = @("outlook","excel","winword","powerpnt","msaccess","mspub","visio","thunderbird","soffice.bin")
$SavDocVolLog = "$NameDirectoryLogsVol\$NameDocVolLogs"
$resultatcopieloc = 0
$resultatcopienet = 0
$pasnecessaireloc = 0
$pasnecessairenet = 0
# FIN VARIABLES GLOBALES DEF ET INIT
# =============================
# DEBUT DU PROGRAMME PRINCIPAL
# =============================
# Chargement d'une librairie pour l'affichade de fenetre
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# On tue les appli genantes
foreach ($i in $killappli){
Kill-Process ($i)
}
Start-Sleep -s 2
# Détermination de l'endroit ou effectuer la sauvegarde
# et la validation ou non de la sauvegarde précédente en local
If (!(Test-Path "$NameDirectoryLogsVol")){
Set-Location "$DirectoryBackup"
New-Item -ItemType Directory -Name "$NameDirectoryLogs"
}
$TimesStart = Get-date -Format 'dddd dd MMM yyyy'
$HourStart = Get-Date -Format 'HH"h"mm'
$Tstart = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# SEQUENCE : COPIE RESEAU
## ================================================================
Write-OutputConsole("lancement")
Start-Sleep -s 2
# Test de la disponibilité du serveur, on arrête le programme si le serveur est injoignable
if ((!(Test-Connection -computer $BackupServer -Count 3 -quiet)) -or (!(Test-Connection -computer $BackupServerfdqn -Count 5 -quiet))) {
Write-OutputConsole("nosynolog")
Show-MessageBox ("Attention !!", "Le serveur de backup n'est pas joignable, la sauvegarde est annulée`nContactez votre administrateur.`n`nCliquez su OK pour Eteindre")
exit
}
# Lancement de la copie Y sur CLUSTER_SYNOLOG
robocopy "$DirectoryBackup" "$DirBackVol" /MIR /R:3 /W:5 /XD $DirectoryExclude >> $SavDocVolLog
$DocVolExitCode = $LASTEXITCODE
if ($DocVolExitCode -lt 8){
# La sauvegarde Locale est réussie, on remet le fichier flag puis on compresse le tout dans le dossier du jour
set-content -path "$fichierflagnet" -value "OK"
$resultatcopienet = 1
}
$TimesEnd = Get-date -Format 'dddd dd MMM yyyy'
$HourEnd = Get-Date -Format 'HH"h"mm'
$Tend = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# 3EME SEQUENCE : INDICATEURS/NOTIFICATIONS
# ================================================================
Delete-Logs $NameDirectoryLogsVol 8
if ($resultatcopienet -eq 1) {
$messagecourriel = "Résultat de la sauvegarde : OK (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Si la sauvegarde a déja été exécutée dans les 18h, elle n'est pas relancée."
$toSupport = $null
}
else {
$messagecourriel = "Un problème est survenu dans l'exécution de votre sauvegarde (démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd)"
$body = "Un problème est survenu dans l'exécution de la sauvegarde pour $UserName. survenu lors de la sauvegarde de Copie-Y démarrée le $TimesStart à $HourStart et terminée le $TimesEnd à $HourEnd.`n`nLes résultats de sauvegardes ont été les suivants :`n`nCopie-Y vers CLUSTER_SYNOLOG `n"+$ExitCode["$DocVolExitCode"]+"`n`Pour de plus amples détails, consultez le fichier log en pièce jointe."
}
If (!(Test-Path "$SavDocVolLog")){
$SavDocVolLog = $null
}
# Message aux utilisateurs
Send-Email $mailfrom $Toclient $toSupport 'High' $messagecourriel $body $SavDocVolLog $SmtpServerName
# TODO:verifier le lancement de la commande mail
# INDICATEURS :
# ------------
#
Set-indicator($indicateurs)
}
{
Exit
}

613
robocopy-backup.ps1 Normal file
View File

@@ -0,0 +1,613 @@
# =======================================================
# Fonction qui ecrit les messages sur la sortie standard
# Usage : Write-OutputConsole ($theme)
# =======================================================
function Write-OutputConsole($theme) {
if ( $theme -eq "lancement") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde en local de Vos Documents, Votre Bureau !"
Write-Output "! et Votre Messagerie est en cours. !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "lancementvol") {
write-Output "!-----------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde sur Serveur distant de Vos Documents, Votre Bureau !"
Write-Output "! et Votre Messagerie est en cours. !"
Write-Output "! !"
Write-Output "! Les fichiers avec les extensions suivantes sont actuellement exclus: !"
Write-Output "! .ogg.flac.mp3.wav.wma.aac.mpeg.ogm.avi.flv.wmv.mov.divx.xvid !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "------------------------------------------------------------------------------!"
}
if ( $theme -eq "zipprob") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La compression de la messagerie a echoué !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! Fermer cette Fenêtre Annulera la Sauvegarde ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "nospace") {
write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Disque dur C Local n'a pas assez d'espace Libre !"
Write-Output "! !"
Write-Output "! La sauvegarde est annulée !"
Write-Output "! Contactez votre administrateur. !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "noaubrac") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! Le Serveur de Sauvegarde est indiponible !"
Write-Output "! !"
Write-Output "! !"
Write-Output "! La Sauvegarde distante est Annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagloc") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Locale de Vos Documents, Votre Bureau !"
Write-Output "! et Votre Messagerie a déja  été lancée !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
if ( $theme -eq "pasdeflagnet") {
Write-Output "!-------------------------------------------------------------------------------!"
Write-Output "! La Sauvegarde Réseau de Vos Documents, Votre Bureau !"
Write-Output "! et Votre Messagerie a déja  été lancée !"
Write-Output "! lors de ces dernières 24 heures !"
Write-Output "! La Sauvegarde est donc annulée ! !"
Write-Output "! !"
Write-Output "--------------------------------------------------------------------------------!"
}
}
# =======================================================
# Fonction qui envoie un email avec 2 attachements
# =======================================================
function Send-EMail($argFrom, $argTo, $argtoCC, $argPriority, $argSubject, $argBody, $argAtt, $argAtt2, $argAtt3, $argAtt4, $argSmtp) {
$mail = New-Object System.Net.Mail.MailMessage
$smtpClient = new-object system.net.mail.SmtpClient($argSmtp)
$mail.Body = $argBody
$mail.Subject = $argSubject
$mail.priority = $argPriority
$mail.From = $argFrom
$mail.To.Add($argTo)
if ($argtoCC) {
$mail.CC.Add($argtoCC)
}
if (!($argAtt -eq $null)) {
$att = new-object Net.Mail.Attachment $argAtt
$mail.Attachments.Add($att)
}
if (!($argAtt2 -eq $null)) {
$att2 = new-object Net.Mail.Attachment $argAtt2
$mail.Attachments.Add($att2)
}
if (!($argAtt3 -eq $null)) {
$att = new-object Net.Mail.Attachment $argAtt3
$mail.Attachments.Add($att3)
}
if (!($argAtt4 -eq $null)) {
$att4 = new-object Net.Mail.Attachment $argAtt4
$mail.Attachments.Add($att4)
}
$smtpClient.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$smtpClient.Send($mail)
$mail.Attachments.Dispose()
$mail = $null
$smtpClient = $null
}
# =======================================================================
# Fonction qui affiche une boite de dialogue qui se ferme automatiquement
# =======================================================================
function DisplayMessageBox($argText, $argDelayDisplay, $argTitre, $argButton) {
$job=Start-Job -ArgumentList $argText,$argDelayDisplay,$argTitre,$argButton -ScriptBlock {
$a = new-object -comobject wscript.shell
$a.popup($args[0],$args[1],$args[2],$args[3])
}
return $job;
}
# =================================================================================================
# DESCRIPTION: Displays the attention message box & checks to see if the user clicks the ok button.
# Affiche une boite de dialogue fenêtrée
# Prérequis [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# =================================================================================================
function Show-MessageBox([string] $Message,[string] $Titre="Attention !!", [String] $IconType="Warning",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
function Show-QuestionBox([string] $Message,[string] $Titre="Question ??", [String] $IconType="Question",[String] $BtnType="YesNo") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."
}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre,[Windows.Forms.MessageBoxButtons]::$BtnType, [Windows.Forms.MessageBoxIcon]::$IconType)
}
function Show-InfoBox([string] $Message,[string] $Titre="Pour votre Information !!", [String] $IconType="Information",[String] $BtnType="Ok") {
trap {
switch ($_.Exception.GetType().FullName) {
"System.Management.Automation.PSInvalidCastException" {$_.message;Break}
"System.Management.Automation.RuntimeException" {
Throw "Assurez-vous que l'assembly [System.Windows.Forms] est bien chargé."}
default {Throw $_}
}#switch
}#trap
return [Windows.Forms.MessageBox]::Show($Message,$Titre, $BtnType,$IconType)
}
# =================================================
# Renvoi la Taille d'un repertoire en octets
# =================================================
function Get-FolderSize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
# =================================================
# Renvoi la Taille d'un fichier en octet
# =================================================
function Get-FileSize($Path) {
# On verifie si le path exist
if(test-path $Path){
$colItems = (Get-ChildItem $Path)
return $colItems.Length
}
else {
return 0
}
}
# ==================================================
# Renvoie la Taille d'un fichier en Go
# ==================================================
function Get-FileSizeGB($Path){
return ("{0:N2}" -f ((Get-FileSize $Path) /1GB))
}
# ===========================================================
# Nettoyage des Logs
# ===========================================================
function Delete-Logs($argDirectoryLogs,$argDelay){
$jour = [DateTime]::Today
$lastMod = $jour.AddDays(-$argDelay)
#Récupere la liste des fichiers logs antérieurs a  la date
$Files = get-childitem $argDirectoryLogs -include *.log -recurse | Where {$_.LastWriteTime -le "$lastMod"}
if (!($Files -eq $null)) {
foreach ($File in $Files) {
write-host $File
Remove-Item $File
}
}
}
# =========================================================================
# Fonction de récupération du mail utilisateur dans le fichier sur aubrac
# =========================================================================
function Get-Email {
param ([string]$login,[string]$filelogs)
Get-Content $filelogs | Where-Object { $_.split(";")[0] -match "$login"} | foreach {$_ -replace "^$login;", ""}
}
# =======================================================
# Fonction qui initialise le bon path de la messagerie
# =======================================================
function Find-DirectoryMessagerie {
param ([string]$pathDocsUserLocation)
Set-Location $pathDocsUserLocation
Get-ChildItem "./" | Where-Object {$_.Attributes -eq "Directory"} | Where-Object {$_.Name -match "^[M-m]essagerie$"} | foreach {$_.FullName}
}
# =========================================================================
# Fonctions relatives a  la taille du disque C
# =========================================================================
function Get-FreeSpaceCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace/1GB,2)}
}
function Get-FreeSpaceC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
}
function Get-SizeC {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
}
function Get-SizeCGB {
return Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size/1GB,2)}
}
function espacedispo
{
$freespaceC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.FreeSpace}
$sizeC = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {$_.Size}
$freespaceCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.FreeSpace / 1073741824,2)}
$sizeCGB = Get-WmiObject win32_logicaldisk -Filter "DriveType=3" | Where-Object {$_.DeviceID -eq "C:"} | ForEach-Object {[Math]::round($_.Size / 1073741824,2)}
$docspace = (Get-FolderSize $DocsUserLocation).Sum
$burspace = (Get-FolderSize $BureauUserLocation).Sum
$totaltoback = $burspace + $docspace
$docspaceGB = [Math]::round($docspace/1GB,2)
$totaltobackGB = [Math]::round($totaltoback/1GB,2)
$spaceminfree = $totaltoback + 21474836480
echo $spaceminfree
echo $freespaceCGB
if
( $freespaceC -lt $spaceminfree )
{
$greenflag = 1
}
else
{
$greenflag = 0
}
return $greenflag
}
function Kill-Process ($app) {
if (Get-Process $app -ErrorAction silentlycontinue) {
Get-Process $app | Stop-Process
Start-Sleep -s 2
}
}
function Get-OS {
return (Get-WmiObject -class Win32_OperatingSystem).Caption | foreach {$_ -replace " ", ""}
}
#=======================================================
# Fonction qui défini laptop ou desktop
# =======================================================
function Get-PCtype {
return (Get-WmiObject -class Win32_computersystem).PCSystemType }
$pctype = Get-PCtype
if ($pctype -ne "2")
{$fixe = "Oui"}
else
{$fixe = "Non"}
# =======================================================
# Fonction qui écrit des indicateurs dans un fichier
# =======================================================
function Set-Indicator($fichier) {
#Si le fichier n'existe pas, je crée un nouveau fichier.
if ((Test-Path $fichier) -ne "True") { New-Item -ItemType file -Path $indicateurs -Force }
# Ajoute une ligne dans le fichier.
# Les champs sont l'utilisateur, l'ordinateur, les 5 codes de sortie des commandes robocopy, les dates de debut et de fin, la taille en GB a copier a distance
# et l'espace libre suffisant Oui ou Non
Add-Content -Path $fichier -Value "$UserName;$ComputerName;$DocExitCode;$BurExitCode;$MailZipExitCode;$BurVolExitCode;$DocVolExitCode;$Tstart;$Tend;$sizetobackGB;$nospace"
}
# =======================================================
# Déclaration des variables globales
# =======================================================
# Portable ou Fixe
#$fixe = "Oui"
# Serveur de backup
$BackupServer = "aubrac"
# Serveur de Backup FQDN
$BackupServerfdqn = "aubrac.iut.local"
# Répertoire partagé sur le serveur
$ShareBackupServer = "sauvegarde"
# Répertoire sauvegarde local
$NameDirectoryBackup = "sauvegarde"
# Nom de l'ordinateur
$ComputerName = $Env:COMPUTERNAME
# Nom de la session
$UserName = $Env:USERNAME
# Initialisation du jour de la semaine
$numjour = Get-Date -UFormat %u
# Initialisation du Jour de l'année
$dayofyear = (get-date).dayofyear
# Répertoire de sauvegarde sur le serveur aubrac
$DirBackVol = "\\$BackupServer\$ShareBackupServer\$UserName\$ComputerName"
# Nom du repertoire de logs
$NameDirectoryLogs = "logssauv"
# Nom du repertoire de logs Local
$NameDirectoryLogsLocal = "localogssauv"
# Nom du serveur smtp
$SmtpServerName = "relay.iut-rodez.fr"
# Mail du support
$toSupport = "support2@iut-rodez.fr"
# Emplacement du fichier de correspondance des emails (attention a  ce qu'il ne soit pas modifié par des utilisateurs!)
$filelogins = "\\$BackupServer\$ShareBackupServer\logssauv\login-email.csv"
# Champ FROM des courriel
if ((Test-Path $filelogins) -ne "True") {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$mailfrom = "sauvegarde@iut-rodez.fr" }
else {
$mailfrom = Get-EMail $UserName $filelogins
}
}
if ((Test-Path $filelogins) -ne "True") {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
if (( Get-Content "$filelogins" | ? { $_ -match "$UserName" } ) -eq $Null ) {
$Toclient = "sauvegarde@iut-rodez.fr" }
else {
$Toclient = Get-EMail $UserName $filelogins
}
}
# Fichier des indicateurs sur \\aubrac\sauvegarde\
$indicateurs = "\\$BackupServer\$ShareBackupServer\logssauv\indicateurs$dayofyear.txt"
# Localisation du profil des utilisateurs (XP ou seven)
$ProfileUserLocation = $Env:UserProfile
$DirectoryBackup = "$ProfileUserLocation\sauvegarde"
$DocsUserLocation = [Environment]::GetFolderPath("MyDocuments")
$DirectoryExclude = "$DocsUserLocation\Ma musique"
$DirectoryExclude1 = "$DocsUserLocation\Mes images"
$DirectoryExclude2 = "$DocsUserLocation\Mes vidéos"
$DocsDestBackup = "$DirBackVol\Documents"
$DocsDestBackupLocal = "$DirectoryBackup\Documents"
$BureauUserLocation = [Environment]::GetFolderPath("Desktop")
$BureauDestBackup = "$DirBackVol\Bureau"
$BureauDestBackupLocal = "$DirectoryBackup\Bureau"
$NameDirectoryLogsVol = "$DocsUserLocation\Logssauv"
$NameDirectoryLogsLoc = "$DocsUserLocation\Localogssauv"
$fichierflagloc = "$DirectoryBackup\flag-loc.txt"
$fichierflagnet = "$DirectoryBackup\flag-net.txt"
$os = Get-OS
#Liste des fichiers a  exclure
$FileExclude = "`"*.ogg`" `"*.flac`" `"*.mp3`" `"*.wav`" `"*.wma`" `"*.aac`" `"*.mpeg`" `"*.ogm`" `"*.avi`" `"*.flv`" `"*.wmv`" `"*.mov`" `"*.divx`" `"*.xvid`" "
# Nom du fichier logs
$NameFileDocsLogs = "SavDoc"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$NameFileBurLogs = "SavBur"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$NameDocVolLogs = "SavDocVol"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$NameBurVolLogs = "SavBurVol"+" {0:dddd dd MMM yyyy' - 'HH'h'mm}.log" -f (Get-Date)
$DelayRetentionLogs = 8
$listJob = @()
$ExitCode = @{
"16"="Erreur fatale lors de l'opération. Voir fichier de Log"
"15"="Echec de la copie. Voir le fichier de Log."
"14"="Echec de la copie. Voir le fichier de Log."
"13"="Echec de la copie. Voir le fichier de Log."
"12"="Echec de la copie. Voir le fichier de Log."
"11"="Echec de la copie. Voir le fichier de Log."
"10"="Echec de la copie. Voir le fichier de Log."
"9"="Echec de la copie. Voir le fichier de Log."
"8"="Echec de la copie. Plisieurs fichiers n'ont pas été copiés. Voir le fichier de Log."
"7"="Copie OK. Certains fichiers présents et supplémentaires on généré une incohérence entre la source et la destination. Voir le fichier de Log."
"6"="Copie OK. Certains fichiers et dossiers suplémentaires ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"5"="Copie OK. Certains fichiers ont été copiés et d'autres ont généré une incohérence entre la source et la destination. Voir le fichier de Log."
"4"="Copie OK. Une incohérence entre la source et la destination de la sauvegarde a été détectée. Voir le fichier de Log."
"3"="Copie OK. Certains fichiers supplémentaires ont été copiés avec succès."
"2"="Copie OK. Certains fichiers ou répertoires supplémentaires ont été détectés et copiés avec succès."
"1"="Copie OK. Un ou plusieurs fichiers ont été copiés avec succès du répertoire source au répertoire de destination."
"0"="Copie OK. Aucun changement. Le répertoire source était identique au répertoire de destination."
}
$mail = New-Object System.Net.Mail.MailMessage
$killappli = @("outlook","excel","winword","powerpnt","msaccess","mspub","visio","thunderbird","soffice.bin")
$SavDocLoglocal = "$NameDirectoryLogsLoc\$NameFileDocsLogs"
$SavDocVolLog = "$NameDirectoryLogsVol\$NameDocVolLogs"
$SavBurLoglocal = "$NameDirectoryLogsLoc\$NameFileBurLogs"
$SavBurVolLog = "$NameDirectoryLogsVol\$NameBurVolLogs"
$resultatcopieloc = 0
$resultatcopienet = 0
$pasnecessaireloc = 0
$pasnecessairenet = 0
# FIN VARIABLES GLOBALES DEF ET INIT
# =============================
# DEBUT DU PROGRAMME PRINCIPAL
# =============================
# Chargement d'une librairie pour l'affichade de fenetre
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# On tue les appli genantes
foreach ($i in $killappli){
Kill-Process ($i)
}
Start-Sleep -s 2
# Détermination de l'endroit ou effectuer la sauvegarde
# et la validation ou non de la sauvegarde précédente en local
If (!(Test-Path "$DirectoryBackup")){
Set-Location "$ProfileUserLocation"
New-Item -ItemType Directory -Name "$NameDirectoryBackup"
}
#Test des répertoires acceuillant les logs des backups et création si nécessaire
If (! (Test-Path "$NameDirectoryLogsLoc")){
Set-Location "$DocsUserLocation"
New-Item -ItemType Directory -Name "$NameDirectoryLogsLocal"
}
If (!(Test-Path "$NameDirectoryLogsVol")){
Set-Location "$DocsUserLocation"
New-Item -ItemType Directory -Name "$NameDirectoryLogs"
}
$TimesStart = Get-date -Format 'dddd dd MMM yyyy'
$HourStart = Get-Date -Format 'HH"h"mm'
$Tstart = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
# ===============================================================
# 1ERE SEQUENCE : COPIE LOCALE
# ===============================================================
If ( $fixe -eq "Non" ){
$d = Show-QuestionBox ("Question :`n", "Voulez-vous lancer une sauvegarde maintenant ?`n Répondez Oui pour la lancer ou Non pour quitter")}
If ($d -eq [Windows.Forms.DialogResult]::Yes) {
$reponseuser = "Oui"}
else {
$reponseuser = "Non"}
If (($fixe -eq "Oui") -or ( $reponseuser -eq "Oui")){
# Taille brute pour des opérations mathématiques
$sizeDocsUserReal = (Get-FolderSize $DocsUserLocation).Sum
$sizeBurUserReal = (Get-FolderSize $BureauUserLocation).Sum
$sizeDocsVolReal = $sizeDocsUserReal - $sizeMailUserReal
$sizetoback = $sizeBurUserReal + $sizeDocsVolReal
# Taille en Gb reformaté
$sizeDocsUser = [Math]::round($sizeDocsUserReal/1GB,2)
$sizeBurUser = [Math]::round($sizeBurUserReal/1GB,2)
$sizetobackGB = [Math]::round($sizetoback/1GB,2)
# Vérification de l'espace disponible sur le disque local
$space = espacedispo
If ( $space -eq 1 ) { Write-OutputConsole("nospace")
$nospace = 1
Set-indicator($indicateurs)
Show-MessageBox ("Attention !!", "Le Disque dur C Local n'a pas assez d'espace Libre,`n La sauvegarde est annulée`nIl est indispensable de contacter au plus vite votre administrateur.`n`nCliquez su OK pour Eteindre")
}
else {
If ((!(Test-Path "$fichierflagloc")) -or ((Get-item "$fichierflagloc" | where-object {($_.lastwritetime -gt ((Get-date).Addhours(-18)))}) -eq $null)) {
Write-OutputConsole("lancement")
Start-Sleep -s 2
# TODO : peut-être faut-il exlure le répertoire Messagerie?
robocopy "$DocsUserLocation" "$DocsDestBackupLocal" /MIR /R:3 /W:5 /xf $FileExclude /XD $DirectoryExclude $DirectoryExclude1 $DirectoryExclude2 /XA:HS /UNILOG:$SavDocLoglocal
$DocExitCode = $LASTEXITCODE
robocopy "$BureauUserLocation" "$BureauDestBackupLocal" /MIR /R:3 /W:5 /xf $FileExclude /XA:HS /UNILOG:$SavBurLoglocal
$BurExitCode = $LASTEXITCODE }
if ($DocExitCode -lt 8 -and $BurExitCode -lt 8) {
# La sauvegarde Locale est réussie, on remet le fichier flag puis on compresse le tout dans le dossier du jour
set-content -path "$fichierflagloc" -value "OK"
$resultatcopieloc = 1
}
}
}
else {
Write-OutputConsole("pasdeflagloc")
Start-Sleep -s 5
$pasnecessaireloc = 1
}
## ===============================================================
# 2EME SEQUENCE : COPIE RESEAU
# ================================================================
If ((!(Test-Path "$fichierflagnet")) -or ((Get-item "$fichierflagnet" | where-object {($_.lastwritetime -gt ((Get-date).Addhours(-18)))}) -eq $null)){
Write-OutputConsole("lancementvol")
Start-Sleep -s 2
# Test de la disponibilité du serveur, on arrête le programme si le serveur est injoignable
if ((!(Test-Connection -computer $BackupServer -Count 3 -quiet)) -or (!(Test-Connection -computer $BackupServerfdqn -Count 5 -quiet))) {
Write-OutputConsole("noaubrac")
Show-MessageBox ("Attention !!", "Le serveur de backup n'est pas joignable, la sauvegarde est annulée`nContactez votre administrateur.`n`nCliquez su OK pour Eteindre")
exit
}
# Lancement de la copie du Bureau sur aubrac
robocopy "$BureauUserLocation" "$BureauDestBackup" /MIR /R:3 /W:5 /UNILOG:$SavBurVolLog
$BurVolExitCode = $LASTEXITCODE
# Lancement de la copie des Docs sur aubrac sans la Messagerie
robocopy "$DocsUserLocation" "$DocsDestBackup" /MIR /R:3 /W:5 /XD $DirectoryExclude $DirectoryExclude1 $DirectoryExclude2 /UNILOG:$SavDocVolLog
$DocVolExitCode = $LASTEXITCODE
if ($BurVolExitCode -lt 8 -and $DocVolExitCode -lt 8){
# La sauvegarde Locale est réussie, on remet le fichier flag puis on compresse le tout dans le dossier du jour
set-content -path "$fichierflagnet" -value "OK"
$resultatcopienet = 1
}
}
else {
Write-OutputConsole("pasdeflagnet")
Start-Sleep -s 2
$pasnecessairenet = 1
}
$TimesEnd = Get-date -Format 'dddd dd MMM yyyy'
$HourEnd = Get-Date -Format 'HH"h"mm'
$Tend = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
## ===============================================================
# 3EME SEQUENCE : INDICATEURS/NOTIFICATIONS
# ================================================================
Delete-Logs $NameDirectoryLogsLoc 8
Delete-Logs $NameDirectoryLogsVol 8
if (($pasnecessaireloc -eq 1) -and ($pasnecessairenet -eq 1)) {
exit
}
elseif ((($pasnecessaireloc -eq 1) -and ($resultatcopienet -eq 1)) -or (($resultatcopieloc -eq 1) -and ($pasnecessairenet -eq 1))) {
$messagecourriel = "Résultat de la sauvegarde : OK (démarrée le $TimesStart a  $HourStart et terminée le $TimesEnd a  $HourEnd)"
$body = "Si la sauvegarde a déja été exécutée dans les 18h, elle n'est pas relancée.`n`nUne des sauvegardes (soit Locale soit Distante) n'était pas nécessaire et n'a pas été lancée"
$toSupport = $null
}
elseif (($resultatcopieloc -eq 1) -and ($resultatcopienet -eq 1)) {
$messagecourriel = "Résultat de la sauvegarde : OK (démarrée le $TimesStart a  $HourStart et terminée le $TimesEnd a  $HourEnd)"
$body = "Si la sauvegarde a déja été exécutée dans les 18h, elle n'est pas relancée."
$toSupport = $null
}
else {
$messagecourriel = "Un problème est survenu dans l'exécution de votre sauvegarde (démarrée le $TimesStart a  $HourStart et terminée le $TimesEnd a  $HourEnd)"
$body = "Un problème est survenu dans l'exécution de la sauvegarde pour $UserName. survenu lors de la sauvegarde des Documents et du Bureau démarrée le $TimesStart a  $HourStart et terminée le $TimesEnd a  $HourEnd.`n`nLes résultats de sauvegardes ont été les suivants :`n`nDocuments`n"+$ExitCode["$DocExitCode"]+" `n`nBureau `n"+$ExitCode["$BurExitCode"]+" `n`nZip vers aubrac `n"+$ExitCode["$MailZipExitCode"]+" `n`nBureau vers aubrac `n"+$ExitCode["$BurVolExitCode"]+" `n`nDocuments vers aubrac `n"+$ExitCode["$DocVolExitCode"]+"`n`Pour de plus amples détails, consultez le fichier log en pièce jointe."
}
If (!(Test-Path "$SavDocLoglocal")){
$SavDocLoglocal = $null
}
If (!(Test-Path "$SavDocVolLog")){
$SavDocVolLog = $null
}
If (!(Test-Path "$SavBurLoglocal")){
$SavBurLoglocal = $null
}
If (!(Test-Path "$SavBurVolLog")){
$SavBurVolLog = $null
}
# Message aux utilisateurs
Send-Email $mailfrom $Toclient $toSupport 'High' $messagecourriel $body $SavDocLoglocal $SavDocVolLog $SavBurLoglocal $SavBurVolLog $SmtpServerName
# TODO:verifier le lancement de la commande mail
# INDICATEURS :
# ------------
#
Set-indicator($indicateurs)
{
Exit
}

Binary file not shown.

View File

@@ -0,0 +1 @@
Invoke-Command -ComputerName $Name -ScriptBlock {& "\\swpdm\image\2015_SP3.0\startswinstall.exe"} -Credential $Cred -Authentication CredSSP