This commit is contained in:
2023-07-04 12:59:44 +02:00
parent 2cef42a718
commit 09c2faad93
231 changed files with 261001 additions and 4 deletions

View File

@ -0,0 +1,13 @@
#Corriger les problèmes d'ouverture de session très lente, écran noir, performance sur serveur et serveur RDS
#Recommandé
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy" -Name "DeleteUserAppContainersOnLogoff" -Value 1
Logoff
#Autre méthode, supprimer les clés de registre
Remove-Item HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\Configurable\System
New-Item HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\Configurable\System
Remove-Item HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules
New-Item HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules
Remove-Item HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Notifications -Recurse
New-Item HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Notifications

View File

@ -0,0 +1,44 @@
$onesync = (Get-ChildItem 'HKLM:\System\CurrentControlSet\Services' | ? { $_.PSChildName -like "OneSync*" }).Name
$Services =
@("bthserv - Bluetooth Support Service.", "bthserv"),
("DcpSvc - DataCollectionPublishingService.", "DcpSvc"),
("DPS - Diagnostic Policy Service.", "DPS"),
("WdiServiceHost - Diagnostic Service Host.", "WdiServiceHost"),
("WdiSystemHost - Diagnostic System Host.", "WdiSystemHost"),
("DiagTrack - Connected User Experiences and Telemetry [Diagnostics Tracking Service].", "DiagTrack"),
("dmwappushservice - dmwappushsvc.", "dmwappushservice"),
("MapsBroker - Downloaded Maps Manager.", "MapsBroker"),
("lfsvc - Geolocation Service.", "lfsvc"),
("UI0Detect - Interactive Services Detection.", "UI0Detect"),
("SharedAccess - Internet Connection Sharing [ICS].", "SharedAccess"),
("lltdsvc - Link-Layer Topology Discovery Mapper.", "lltdsvc"),
("diagnosticshub.standardcollector.service - Microsoft [R] Diagnostics Hub Standard Collector Service.", "diagnosticshub.standardcollector.service"),
("NcbService - Network Connection Broker.", "NcbService"),
("NcaSvc - Network Connectivity Assistant.", "NcaSvc"),
("defragsvc - Optimize drives.", "defragsvc"),
("wercplsupport - Problem Reports and Solutions Control Panel.", "wercplsupport"),
("PcaSvc - Program Compatibility Assistant Service.", "PcaSvc"),
("QWAVE - Quality Windows Audio Video Experience.", "QWAVE"),
("RmSvc - Radio Management Service.", "RmSvc"),
("SysMain - Superfetch.", "SysMain"),
("TapiSrv - Telephony.", "TapiSrv"),
("UALSVC - User Access Logging Service.", "UALSVC"),
("WerSvc - Windows Error Reporting Service.", "WerSvc"),
("wisvc - Windows Insider Service.", "wisvc"),
("icssvc - Windows Mobile Hotspot Service.", "icssvc"),
("XblAuthManager - Xbox Live Auth Manager.", "XblAuthManager"),
("XblGameSave - Xbox Live Game Save.", "XblGameSave")
foreach ($Service in $Services) {
Write-Host Disabling service $Service[0] -ForegroundColor Cyan
Invoke-Expression ("Set-Service " + $Service[1] + " -StartupType Disabled")
Get-Service $Service[1] | Stop-Service -Force
Start-Sleep 2
}
Set-Location HKLM:\
ForEach ($sync in $onesync) {
Set-ItemProperty -Path $sync -Name Start -Value 4
}
Get-Service OneSync* | Stop-Service -Force

View File

@ -0,0 +1,89 @@
[securestring]$Password = ConvertTo-SecureString 'Password' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PsCredential(".\Admin", $Password)
$ReportsPath = (Join-Path $env:LOCALAPPDATA "Hitea\AmInf\Reports")
New-Item -Path $ReportsPath -ItemType Directory -Force | Out-Null
$VMhost = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop
$TestHostReports = Get-ChildItem -Path (Join-Path $ReportsPath "$($VMhost.CSName)_*.csv")
Write-Host ""
Write-Host "Export reports path: $ReportsPath"
Write-Host ""
Write-Host "Get infos of Host : $($vmhost.CSName)"
Write-Host ""
if (!$TestHostReports) {
$RestartEvents = Get-EventLog -Logname System -After (Get-Date).AddHours(-24) | Where-Object { $_.EventID -in (6005, 6006, 6008, 6009, 1074, 1076) }
$Win32Apps = Get-WmiObject -Class Win32_Product
$WinAppx = Get-AppxPackage
$ServerDetail = [pscustomobject]@{
Computername = $vmhost.CSName
OperatingSystem = $vmhost.Caption
TotalMemory = $vmhost.totalVisibleMemorySize / 1MB -as [int]
FreeMemory = [Math]::Round($vmhost.FreePhysicalMemory / 1MB, 2)
PctMemoryFree = [Math]::Round(($vmhost.FreePhysicalMemory / $vmhost.totalVisibleMemorySize) * 100, 2)
TotalVirtualMemory = $vmhost.totalVirtualMemorySize / 1MB -as [int]
FreeVirtualMemory = [Math]::Round($vmhost.FreeVirtualMemory / 1MB, 2)
PctVirtualMemoryFree = [Math]::Round(($vmhost.FreeVirtualMemory / $vmhost.totalVirtualMemorySize) * 100, 2)
}
$ServerDetail | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_Infos.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
$RestartEvents | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_Restart_Events.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
$WinAppx | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_AppxPackages.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
$Win32Apps | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_Msis.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
}
Write-Host "Detect HyperV Service"
Write-Host ""
$HyperV = Get-Service HvHost -ErrorAction SilentlyContinue
If ($HyperV.Status -eq "Running") {
try {
Import-Module Hyper-V
$VmsState = [enum]::GetNames([Microsoft.HyperV.Powershell.VMState])
$VmsStatus = [enum]::GetNames([Microsoft.HyperV.Powershell.VMOperationalStatus])
$Vms = Get-VM -VMName *
$Vms | Select-Object Id, Name, State, OperationalStatus, Status, Networkadapters,
@{Name = "MemoryStatus"; Expression = { $_.MemoryStatus } },
@{Name = "MemAssignMB"; Expression = { $_.MemoryAssigned / 1MB } },
@{Name = "PctAssignTotal"; Expression = { [math]::Round(($_.memoryAssigned / ($vmhost.TotalVisibleMemorySize * 1KB)) * 100, 2) } },
@{Name = "MemDemandMB"; Expression = { $_.MemoryDemand / 1MB } },
@{Name = "PctDemandTotal"; Expression = { [math]::Round(($_.memoryDemand / ($vmhost.TotalVisibleMemorySize * 1KB)) * 100, 2) } } | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_VMs.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
Foreach ($Item in $Vms) {
if ($Item.State -eq "Running") {
try {
Write-Host "Get infos of VM : $($Item.Name)"
Write-Host ""
$VmInfos = Invoke-Command -VMId $Item.Id -Credential $Credential -ScriptBlock { Get-CimInstance -ClassName Win32_OperatingSystem }
$VMNetwork = ($Item | Select-Object -ExpandProperty Networkadapters | Select-Object IPAddresses)
$VmInfos | Add-Member -NotePropertyName IPAddresses -NotePropertyValue $VMNetwork
$VmEvents = Invoke-Command -VMId $Item.Id -Credential $Credential -ScriptBlock { Get-EventLog -Logname System -After (Get-Date).AddHours(-24) | Where-Object { $_.EventID -in (6005, 6006, 6008, 6009, 1074, 1076) } }
$VmInfos | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_$($Item.Name)_Infos.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
$VmEvents | Export-Csv -Path (Join-Path $ReportsPath "$($VMhost.CSName)_$($Item.Name)_Events.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation
}
catch {
Write-Output "Get VM infos failed"
}
}
}
}
catch {
}
}

View File

@ -0,0 +1,61 @@
# Liste des serveurs pour le rapport
$ServerList = ""
# Vérifier le fichier
If (!(Test-Path $ServerList)) {
Write-Host "Can not get servers list. Script will not continue" -ForegroundColor Red; Exit
}
$servers = @()
$job_details = ""
Get-Content $ServerList | Foreach-Object { $servers += $_ }
for ($i = 0; $i -lt $servers.length; $i++) {
$ConnectionError = 0
Write-Host "Getting result from server: " $servers[$i]
try {
$Session = New-PSSession -ComputerName $servers[$i]
$WindowsVersion = Invoke-Command -session $session -ScriptBlock { (Get-WmiObject win32_operatingsystem).version }
if ($WindowsVersion -match "6.1")
{ $WBSummary = Invoke-Command -session $session -ScriptBlock { add-pssnapin windows.serverbackup; Get-WBSummary } }
else { $WBSummary = Invoke-Command -session $session -ScriptBlock { Get-WBSummary } }
Remove-PSSession $Session
}
catch {
Write-Host "Error connecting remote server"
write-host "Caught an exception:" -ForegroundColor Red
write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
$ConnectionError = 1
}
$job_details += "## Serveur : " + $servers[$i] + "`n"
if ($ConnectionError -eq 1) {
$job_details += "- **Statut** : Error connecting remote server`n"
}
else {
if ($WBSummary.LastBackupResultHR -eq 0) { $job_details += "- **Statut** : Success`n"; $result = "Success" }
else { $job_details += "- **Statut** : Failure`n"; $result = "Failure" }
$job_details += "- **Date** : " + $WBSummary.LastSuccessfulBackupTime + "`n"
if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)) { $job_details += "- **Message** : Success`n"; $message = "Success" }
else { $job_details += "- **Message** : " + $WBSummary.DetailedMessage + "`n"; $message = $WBSummary.DetailedMessage }
$job_details += "- **Nombre de sauvegardes** : " + $WBSummary.NumberOfVersions + "`n"
if ([string]::IsNullOrEmpty($WBSummary.LastBackupTarget)) { $job_details += "- **Destination** : None`n" }
else { $job_details += "- **Destination** : " + $WBSummary.LastBackupTarget + "`n" }
Write-Host "Last Backup Result: $result"
Write-Host "Last Successful Backup Time:" $WBSummary.LastSuccessfulBackupTime
Write-Host "Detailed Message: $message"
Write-Host "Number of Backups:" $WBSummary.NumberOfVersions
Write-Host "Destination:" $WBSummary.LastBackupTarget
Write-Host "-----------------------------------------------------------------"
}
}

View File

@ -0,0 +1,45 @@
Function Install-WacApp {
[CmdletBinding(
SupportsShouldProcess = $true
)]
param (
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[ValidateSet("generate", "installed")]
[string]$CertOption = "generate",
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[int]$Port = 443
)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Output = (Join-Path $env:TEMP "WAC.msi")
$Logfile = (Join-Path $env:TEMP "WAC.txt")
Write-Host "Start Download to temp folder to $Output" -ForegroundColor Green
Invoke-WebRequest "https://aka.ms/WACDownload" -OutFile "$Output"
if ($CertOption -eq "generate") {
$msiArgs = @("/i", "$Output", "/qn", "/L*v", "$Logfile", "SME_PORT=$($Port)", "SSL_CERTIFICATE_OPTION=$($CertOption)")
}
elseif ($CertOption -eq "installed") {
$Thumbprint = Read-Host "Enter un certificate Thumbprint"
$msiArgs = @("/i", "$Output", "/qn", "/L*v", "$Logfile", "SME_PORT=$($Port)", "SME_THUMBPRINT=$($Thumbprint)", "SSL_CERTIFICATE_OPTION=$($CertOption)")
}
else {
return
}
Write-Host "Start Install WAC with port $Port, view logs at $Logfile" -ForegroundColor Green
Start-Process msiexec.exe -ArgumentList $msiArgs -Wait -PassThru -Verb "RunAs"
Write-Host "Create firewall rules for WAC access on any profiles" -ForegroundColor Green
New-NetFirewallRule -DisplayName "Allow Windows Admin Center" -Direction Outbound -profile Any -LocalPort $Port -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow Windows Admin Center" -Direction Inbound -profile Any -LocalPort $Port -Protocol TCP -Action Allow
}

View File

@ -0,0 +1,5 @@
New-SelfSignedCertificate -Subject CertName -DnsName "CertFqdn” -CertStoreLocation “cert:\LocalMachine\My” -KeyAlgorithm RSA -KeyLength 2048 -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(5)
$pwd = ConvertTo-SecureString -String "Password" -Force AsPlainText
Export-PfxCertificate -cert cert:\localMachine\my\785810C7545A00609AA3623159DA3E6E01F265DB -FilePath e:\cert.pfx -Password $pwd

1
Windows Server/README.md Normal file
View File

@ -0,0 +1 @@
# Windows Server

View File

@ -0,0 +1,18 @@
#Forcer la deconnexion de l'agent
azcmagent disconnect --force-local-only
#Désintaller les applications Agent et Proxy AAD
Get-ChildItem -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall | `
Get-ItemProperty | `
Where-Object { $_.DisplayName -eq "Azure Connected Machine Agent" } | `
ForEach-Object { MsiExec.exe /x "$($_.PsChildName)" /qn }
Get-ChildItem -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall | `
Get-ItemProperty | `
Where-Object { $_.DisplayName -eq "Microsoft Azure Active Directory Application Proxy Connector" } | `
ForEach-Object { MsiExec.exe /x "$($_.PsChildName)" /qn }
Get-ChildItem -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall | `
Get-ItemProperty | `
Where-Object { $_.DisplayName -eq "Microsoft Azure AD Application Proxy Connector Updater" } | `
ForEach-Object { MsiExec.exe /x "$($_.PsChildName)" /qn }

View File

@ -0,0 +1,77 @@
#Définition des variables
$ServerBroker = "Srv-Broker.domain.local"
$ServerHost = "Srv-Host.domain.local"
$webhook = "Teams WebHook URL"
$TempLocalPath = "$env:Temp"
$LogTempFile = $TempLocalPath + "\" + ($ServerHost) + "_" + (Get-Date -UFormat "%d-%m-%Y") + ".log"
$LogFolder = "C:\Log_Folder"
#Reprise d'un fonction de log
Function Write-Log {
param (
[Parameter(Mandatory = $True)]
[string]$LogOutput,
[Parameter(Mandatory = $False)]
[string]$LogPath = $LogTempFile
)
if (! (Test-Path $LogFolder)) {
New-Item -Path $LogFolder -ItemType Directory
}
$currentDate = (Get-Date -UFormat "%d-%m-%Y")
$currentTime = (Get-Date -UFormat "%T")
"[$currentDate $currentTime] $logOutput" | Out-File $LogPath -Append
}
Write-Log -LogOutput ("Heure de début $(Get-Date -UFormat "%T")")
#Récupérer les sessions activent sur l'hôte RDS
$Sessions = Get-RDUserSession -ConnectionBroker $ServerBroker | Where-Object HostServer -eq $ServerHost
#Parcourir les sessions activent pour les déconnecter avant le redémarrage
foreach ($Session in $Sessions) {
#Ecriture d'un événement Windows
Write-EventLog -LogName "System" -Source "EventLog" -EventId 6013 -EntryType Information -Message "Session $($Session.UserName) fermée"
Write-Log -LogOutput ("Session $($Session.UserName) fermée")
#Déconnexion des sessions
Invoke-RDUserLogoff -HostServer $ServerHost -UnifiedSessionID $Session.UnifiedSessionID -Force
}
try {
#Redémarrge du serveur et attente de la connectivité WinRM pour validation
Restart-Computer -ComputerName $ServerHost -Wait -For WinRM -Delay 30 -Timeout 3600
Write-Log -LogOutput ("$ServerHost redémarré")
}
catch {
Write-Log -LogOutput ("Erreur de redémarrage serveur: $ServerHost")
}
Write-Log -LogOutput ("Heure de fin $(Get-Date -UFormat "%T")")
$Logcontent = Get-Content $LogTempFile
Copy-Item $LogTempFile -Destination $LogFolder
#Création du JSON pour la notification
$body = @{
"@type" = "MessageCard"
"@context" = "<http://schema.org/extensions>"
"title" = 'Rapport de redémarrage serveur'
"themeColor" = '0055DD'
"text" = "Serveur: " + $ServerHost
"sections" = @(
@{
"activityTitle" = 'Logs'
"activitySubtitle" = 'Chemin du fichier: ' + $LogFolder
"activityText" = $Logcontent
}
)
} | ConvertTo-JSON
#Envoi du message sur teams
Invoke-RestMethod -Method post -ContentType 'application/json; charset=utf-8' -Body $body -Uri $webhook

View File

@ -0,0 +1,14 @@
#A faire sur un controleur de domaine par exemple
#Si le controleur est une VM Hyper-V, il faut déactiver la synchro de l'heure pour cette VM
#Sur le DC
w32tm /config /update /manualpeerlist:"time.windows.com,0x8" /syncfromflags:MANUAL
Restart-Service w32time
w32tm /resync
#Vérifier la propagation sur les PC du domaine
w32tm /resync
w32tm /query /status
#Vérifier la source de temps
w32tm /query /source