Get-PowerShellVersionReport.ps1

<#PSScriptInfo
.VERSION 1.0.0
.GUID 9883f16c-78e3-5593-81ae-527389565819
.AUTHOR Torsten Weise
.COMPANYNAME powerscripting.de
.COPYRIGHT (c) 2026 Torsten Weise. MIT-Lizenz.
.TAGS Powerscripting German Monitoring Report Windows Backup PSEdition_Desktop PSEdition_Core
.LICENSEURI https://powerscripting.de/skripte/files/LICENSE.txt
.PROJECTURI https://powerscripting.de/skripte/get-powershellversionreport.html
.ICONURI https://powerscripting.de/assets/icon-192.png
.EXTERNALMODULEDEPENDENCIES ActiveDirectory
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Erste Veröffentlichung in der PowerShell Gallery.
.PRIVATEDATA
#>


<#
.SYNOPSIS
    Zeigt pro Rechner, welche PowerShell-Versionen installiert sind und ob sie noch Sicherheitsupdates bekommen.
 
.DESCRIPTION
    Seit dem 10. November 2026 sind PowerShell 7.4 (LTS) und 7.5 aus dem Support, zusammen mit .NET 8 und 9.
    Geplante Aufgaben, Agenten und Skripte laufen auf vielen Servern aber noch genau damit. Dazu kommt die
    alte PowerShell-2.0-Engine, die auf älteren Systemen noch als Windows-Feature aktiv ist. Mit ihr lassen
    sich Protokollierung und AMSI umgehen (Downgrade-Angriff mit powershell.exe -Version 2).
 
    Das Skript prüft per PowerShell-Remoting auf jedem Rechner:
    - Windows PowerShell 5.1: Version.
    - PowerShell 7 (pwsh): alle Installationen unter Programme\PowerShell, mit Version und Supportstatus.
    - PowerShell 2.0: ob das Feature installiert oder aktiviert ist.
 
    Welche Versionen als unterstützt gelten, steht in der Tabelle $Support am Anfang des Skripts. Pflege sie,
    wenn Microsoft neue Versionen veröffentlicht oder alte aus dem Support nimmt.
 
    Exitcode: 0 ohne Befund, 1 bei Rechnern, die nicht erreichbar sind, 2 bei Versionen ohne Support oder
    aktivem PowerShell 2.0.
 
.PARAMETER ComputerName
    Rechner, die geprüft werden. Ohne Angabe alle aktivierten Server aus dem Active Directory.
 
.PARAMETER IncludeClients
    Ohne -ComputerName auch Arbeitsplätze aus dem AD prüfen, nicht nur Server.
 
.PARAMETER ReportPath
    Ordner für HTML- und CSV-Bericht. Standard: aktueller Ordner.
 
.EXAMPLE
    .\Get-PowerShellVersionReport.ps1
 
    Prüft alle Server aus dem AD.
 
.EXAMPLE
    .\Get-PowerShellVersionReport.ps1 -ComputerName srv-app01, srv-app02 | Where-Object Bewertung -ne 'OK'
 
    Prüft zwei Server und zeigt nur die mit Handlungsbedarf.
 
.NOTES
    Autor: Torsten Weise, powerscripting.de
    Benötigt: WinRM auf den Zielrechnern, ohne Rechnerliste das ActiveDirectory-Modul (RSAT).
    Supportdaten laut Microsoft Learn, Seite "PowerShell Support Lifecycle", Stand November 2026.
    Das Skript liest nur und ändert nichts. PowerShell 2.0 entfernst du mit
    Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root (Clients) oder
    Uninstall-WindowsFeature PowerShell-V2 (Server).
#>

[CmdletBinding()]
param(
    [string[]] $ComputerName,
    [switch] $IncludeClients,
    [string] $ReportPath = (Get-Location).Path
)

# Supportende der PowerShell-7-Linien. Nur die jeweils neueste Patch-Version einer Linie ist unterstützt.
$Support = @{
    '7.0' = [datetime]'2022-12-03'; '7.1' = [datetime]'2022-05-08'; '7.2' = [datetime]'2024-11-08'
    '7.3' = [datetime]'2024-05-08'; '7.4' = [datetime]'2026-11-10'; '7.5' = [datetime]'2026-11-10'
    '7.6' = [datetime]'2028-11-14'
}

if (-not $ComputerName) {
    Import-Module ActiveDirectory -ErrorAction Stop
    $filter = if ($IncludeClients) { 'Enabled -eq $true -and OperatingSystem -like "Windows*"' }
              else { 'Enabled -eq $true -and OperatingSystem -like "*Server*"' }
    $ComputerName = Get-ADComputer -Filter $filter | Select-Object -ExpandProperty DNSHostName | Sort-Object
    Write-Host "$(@($ComputerName).Count) Rechner aus dem AD"
}

$probe = {
    $out = [ordered]@{ WinPS = $PSVersionTable.PSVersion.ToString(); Pwsh = @(); V2 = 'nicht vorhanden' }
    foreach ($root in @($env:ProgramFiles, ${env:ProgramFiles(x86)}) | Where-Object { $_ }) {
        $dir = Join-Path $root 'PowerShell'
        if (Test-Path $dir) {
            foreach ($exe in Get-ChildItem -Path $dir -Filter pwsh.exe -Recurse -Depth 2 -ErrorAction SilentlyContinue) {
                $v = $exe.VersionInfo.ProductVersion -replace '[^\d\.].*$', ''
                $out.Pwsh += [pscustomobject]@{ Version = $v; Pfad = $exe.FullName }
            }
        }
    }
    # PowerShell 2.0: auf Servern als Rollenfeature, auf Clients als optionales Feature
    try {
        if (Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue) {
            $f = Get-WindowsFeature -Name PowerShell-V2 -ErrorAction Stop
            if ($f -and $f.Installed) { $out.V2 = 'installiert' }
        } else {
            $f = Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root -ErrorAction Stop
            if ($f -and $f.State -eq 'Enabled') { $out.V2 = 'aktiviert' }
        }
    } catch { $out.V2 = 'unbekannt' }
    [pscustomobject]$out
}

$now  = Get-Date
$rows = [System.Collections.Generic.List[object]]::new()
foreach ($c in @($ComputerName)) {
    try {
        $r = Invoke-Command -ComputerName $c -ScriptBlock $probe -ErrorAction Stop
        $notes = @()
        $pwshTxt = @()
        foreach ($p in @($r.Pwsh)) {
            $line = ($p.Version -split '\.')[0..1] -join '.'
            $end  = $Support[$line]
            $state = if (-not $end) { 'unbekannte Version' }
                     elseif ($end -lt $now) { "ohne Support seit $($end.ToString('dd.MM.yyyy'))" }
                     elseif ($end -lt $now.AddDays(90)) { "Support endet am $($end.ToString('dd.MM.yyyy'))" }
                     else { 'unterstützt' }
            $pwshTxt += "$($p.Version) ($state)"
            if ($state -notin 'unterstützt') { $notes += "pwsh $($p.Version): $state" }
        }
        if ($r.V2 -in 'installiert', 'aktiviert') { $notes += 'PowerShell 2.0 entfernen' }
        $rating = if ($notes | Where-Object { $_ -like '*ohne Support*' -or $_ -like '*2.0*' }) { 'Handeln' }
                  elseif ($notes) { 'Prüfen' } else { 'OK' }
        $rows.Add([pscustomobject]@{
            Rechner          = $c
            'Windows PowerShell' = $r.WinPS
            'PowerShell 7'   = if ($pwshTxt) { $pwshTxt -join ', ' } else { 'nicht installiert' }
            'PowerShell 2.0' = $r.V2
            Bewertung        = $rating
            Hinweis          = $notes -join '; '
        })
    }
    catch {
        $rows.Add([pscustomobject]@{ Rechner = $c; 'Windows PowerShell' = ''; 'PowerShell 7' = ''; 'PowerShell 2.0' = ''
            Bewertung = 'Nicht erreichbar'; Hinweis = $_.Exception.Message })
    }
}

$order  = @{ 'Handeln' = 0; 'Prüfen' = 1; 'Nicht erreichbar' = 2; 'OK' = 3 }
$sorted = @($rows | Sort-Object @{ e = { $order[$_.Bewertung] } }, Rechner)
$sorted

$stats = $sorted | Group-Object Bewertung | ForEach-Object { "$($_.Name): $($_.Count)" }
Write-Host ($stats -join ' | ')

$title = "PowerShell-Versionen - $($now.ToString('dd.MM.yyyy'))"
$css   = '<style>body{font-family:Segoe UI,Arial,sans-serif;font-size:13px}table{border-collapse:collapse}td,th{border:1px solid #ccc;padding:4px 8px}th{background:#eee}</style>'
$html  = $sorted | ConvertTo-Html -Title $title -Head $css -PreContent "<h2>$title</h2><p>$($sorted.Count) Rechner. $($stats -join ', ').</p>" | Out-String
$html  = $html -replace '<td>Handeln</td>', '<td style="background:#f8d7da">Handeln</td>' `
               -replace '<td>Prüfen</td>', '<td style="background:#fff3cd">Prüfen</td>'
$base  = Join-Path $ReportPath ("PowerShell-Versionen_{0:yyyy-MM-dd}" -f $now)
$html | Set-Content -Path "$base.html" -Encoding UTF8
$sorted | Export-Csv -Path "$base.csv" -NoTypeInformation -Delimiter ';' -Encoding UTF8
Write-Host "Bericht: $base.html und $base.csv"

if (@($sorted | Where-Object Bewertung -eq 'Handeln').Count) { exit 2 }
elseif (@($sorted | Where-Object Bewertung -in 'Prüfen', 'Nicht erreichbar').Count) { exit 1 }
else { exit 0 }