windows-updater/windows-updater.ps1

66 lines
2.6 KiB
PowerShell

# Script Name: windows-updater.ps1
# Beschreibung: Lädt Module offline in Powershell, installiert Windows Updates und startet den Rechner ggf. neu
# Lauffähig unter Windows Server 2016, 2019 und 2022
# Aufruf: -
# Autor: Patrick Asmus
# Web: https://www.media-techport.de
# Git-Reposit.: https://git.media-techport.de/scriptos/windows-updater.git
# Version: 1.1
# Datum: 30.11.2023
# Modifikation: log-dir wird erstellt wenn nicht vorhanden
#####################################################
# Variablen
$LogPfad = "C:\logs\windows-updater.log"
$ModulVerzeichnis = Join-Path -Path $PSScriptRoot -ChildPath "Modules"
$env:PSModulePath += ";$ModulVerzeichnis"
# Funktion zur Formatierung des Datums im deutschen Stil
function Format-DeutschesDatum ([datetime] $date) {
return $date.ToString("dd.MM.yyyy HH:mm:ss")
}
# Überprüfe, ob der Log-Ordner existiert, andernfalls erstelle ihn
if (-not (Test-Path -Path $LogPfad)) {
New-Item -ItemType Directory -Path (Split-Path $LogPfad) -Force
}
# Zeitstempel für das Logfile
$LogZeitstempel = Format-DeutschesDatum (Get-Date)
$LogEintrag = "Windows Updates gestartet am: $LogZeitstempel"
Write-Host $LogEintrag
$LogEintrag | Out-File -Append -FilePath $LogPfad
# Importiere das PSWindowsUpdate-Modul
Import-Module -Name "PSWindowsUpdate" -Verbose
# Überprüfe, ob das Modul erfolgreich geladen wurde
if (Get-Module -Name PSWindowsUpdate -ListAvailable) {
Write-Host "PSWindowsUpdate-Modul erfolgreich geladen."
# Installiere Windows-Updates und speichere die Ausgabe
$Ausgabe = Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
# Überprüfe, ob ein Neustart erforderlich ist
if ($Ausgabe.RestartRequired) {
Write-Host "Ein Neustart ist erforderlich."
} else {
Write-Host "Kein Neustart erforderlich."
}
# Gib die Ausgabe der Windows-Update-Installation in der Kommandozeile aus und schreibe sie ins Logfile
$Ausgabe | ForEach-Object {
$LogMeldung = "ComputerName: $($_.ComputerName) Result: $($_.Result) KB: $($_.KB) Size: $($_.Size) Title: $($_.Title)"
Write-Host $LogMeldung
$LogMeldung | Out-File -Append -FilePath $LogPfad
}
} else {
Write-Host "Fehler beim Laden des PSWindowsUpdate-Moduls."
}
# Zeitstempel für das Logfile nach Abschluss des Skripts
$LogZeitstempel = Format-DeutschesDatum (Get-Date)
$LogEintrag = "Windows Updates beendet am: $LogZeitstempel"
Write-Host $LogEintrag
$LogEintrag | Out-File -Append -FilePath $LogPfad
"----------------------------" | Out-File -Append -FilePath $LogPfad