<# .SYNOPSIS Remote-ServiceAndScan.ps1 - Remote WinRM Malware Scan & Maintenance Tool Published by Cyber Highway LTD (https://www.cyberhighway.co.uk) Bedfordshire | 07378 510 974 | info@cyberhighway.co.uk .DESCRIPTION Connects over WinRM to one or more remote Windows computers and performs: 1. Malware scan: updates Microsoft Defender signatures, runs a Quick or Full scan, and lists any new detections. 2. Maintenance (unless -SkipMaintenance is used): clears old temp files and the Recycle Bin, checks disk health and free space, runs DISM and SFC repairs, and re-trims SSDs. 3. Updates and reboot: triggers a Windows Update scan and checks for a pending reboot. If -Reboot is specified and a reboot is pending, schedules a restart with a 60-second delay. 4. Report: saves a detailed JSON report and prints a summary table. .PARAMETER ComputerName One or more target hostnames or IP addresses reachable over WinRM. .PARAMETER Credential Optional PSCredential with administrator privileges on the target machine(s). .PARAMETER ScanType Microsoft Defender scan type: 'Quick' (default) or 'Full'. .PARAMETER SkipMaintenance Runs the Microsoft Defender malware scan, Windows Update scan, and pending-reboot check only, skipping temp/Recycle Bin cleanup, DISM, SFC, and SSD re-trim. .PARAMETER Reboot Restarts the target machine only if a pending reboot is detected, using a 60-second delay so active sessions can save work. .PARAMETER TempFileAgeDays Age threshold in days for removing old temporary files during maintenance (default: 7). .PARAMETER ReportDir Directory where the JSON report is saved (default: .\Reports). .EXAMPLE .\Remote-ServiceAndScan.ps1 -ComputerName PC01 -Credential (Get-Credential) .EXAMPLE .\Remote-ServiceAndScan.ps1 -ComputerName PC01,PC02 -ScanType Full -Reboot .NOTES Requirements: - Run PowerShell as Administrator on your machine. - Run Enable-PSRemoting -Force on the target. - You need admin rights on the target. - Defender must be the active antivirus on the target. Caveats: - The scan uses Defender's cloud-updated definitions, but no scan catches everything. - A Full scan, DISM and SFC can each take a long time, so test on one PC first. - If a threat is flagged, review it in the report before assuming it's cleaned. #> [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 0)] [string[]]$ComputerName, [Parameter(Mandatory = $false)] [System.Management.Automation.PSCredential]$Credential, [Parameter(Mandatory = $false)] [ValidateSet('Quick', 'Full')] [string]$ScanType = 'Quick', [Parameter(Mandatory = $false)] [switch]$SkipMaintenance, [Parameter(Mandatory = $false)] [switch]$Reboot, [Parameter(Mandatory = $false)] [int]$TempFileAgeDays = 7, [Parameter(Mandatory = $false)] [string]$ReportDir ) $ErrorActionPreference = 'Continue' # Verify local elevation $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Warning 'Please run PowerShell as Administrator on your machine before running Remote-ServiceAndScan.ps1.' } $scriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { (Get-Location).Path } if (-not $ReportDir) { $ReportDir = Join-Path $scriptRoot 'Reports' } New-Item -ItemType Directory -Path $ReportDir -Force -ErrorAction SilentlyContinue | Out-Null $remoteBlock = { param( [string]$ScanMode, [bool]$DoMaintenance, [bool]$DoReboot, [int]$TempDays ) $ErrorActionPreference = 'Continue' $runStart = Get-Date $cutoff = $runStart.AddDays(-$TempDays) function Get-FreeGB { try { return [math]::Round((Get-PSDrive -Name C -ErrorAction Stop).Free / 1GB, 2) } catch { return 0.0 } } $freeBeforeGB = Get-FreeGB # ---- 1. Malware Scan (Microsoft Defender) ---- $defenderInfo = [ordered]@{ AntivirusEnabled = $false SignatureUpdated = $false SignatureVersion = $null ScanType = $ScanMode ScanCompleted = $false ScanError = $null NewDetectionsCount = 0 Detections = @() } try { $mpStatus = Get-MpComputerStatus -ErrorAction Stop $defenderInfo.AntivirusEnabled = [bool]$mpStatus.AntivirusEnabled try { Update-MpSignature -ErrorAction Stop $defenderInfo.SignatureUpdated = $true } catch { $defenderInfo.ScanError = "Signature update warning: $($_.Exception.Message)" } $mpStatusAfter = Get-MpComputerStatus -ErrorAction SilentlyContinue if ($mpStatusAfter) { $defenderInfo.SignatureVersion = $mpStatusAfter.AntivirusSignatureVersion } $mpScanType = if ($ScanMode -eq 'Full') { 'FullScan' } else { 'QuickScan' } Start-MpScan -ScanType $mpScanType -ErrorAction Stop $defenderInfo.ScanCompleted = $true $threats = Get-MpThreatDetection -ErrorAction SilentlyContinue | Where-Object { $_.InitialDetectionTime -ge $runStart.AddMinutes(-5) } if ($threats) { $detList = foreach ($t in $threats) { [pscustomobject]@{ ThreatID = $t.ThreatID ActionSuccess = $t.ActionSuccess InitialDetectionTime = $t.InitialDetectionTime CleaningAction = $t.CleaningAction Resources = ($t.Resources -join '; ') } } $defenderInfo.Detections = @($detList) $defenderInfo.NewDetectionsCount = @($detList).Count } } catch { $defenderInfo.ScanError = $_.Exception.Message } # ---- 2. Maintenance (Temp files, Recycle Bin, Disk Health, DISM, SFC, SSD Re-Trim) ---- $maintenanceInfo = [ordered]@{ Skipped = (-not $DoMaintenance) TempFilesFreedMB = 0.0 RecycleBinCleared = $false FreeSpaceBeforeGB = $freeBeforeGB FreeSpaceAfterGB = $freeBeforeGB Disks = @() DismStatus = 'Skipped' SfcStatus = 'Skipped' SsdReTrimmed = 'Skipped' } if ($DoMaintenance) { # 2a. Clear old temp files $tempDirs = @("$env:WINDIR\Temp") if (Test-Path 'C:\Users') { Get-ChildItem 'C:\Users' -Directory -ErrorAction SilentlyContinue | ForEach-Object { $tempDirs += (Join-Path $_.FullName 'AppData\Local\Temp') } } $bytesFreed = [int64]0 foreach ($td in ($tempDirs | Select-Object -Unique)) { if (Test-Path -LiteralPath $td) { Get-ChildItem -LiteralPath $td -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $cutoff } | ForEach-Object { $len = $_.Length try { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction Stop $bytesFreed += $len } catch {} } } } $maintenanceInfo.TempFilesFreedMB = [math]::Round($bytesFreed / 1MB, 2) # 2b. Empty Recycle Bin try { Clear-RecycleBin -Force -ErrorAction Stop $maintenanceInfo.RecycleBinCleared = $true } catch { $maintenanceInfo.RecycleBinCleared = $false } # 2c. Check disk health and free space try { $disks = Get-PhysicalDisk -ErrorAction Stop | ForEach-Object { [pscustomobject]@{ FriendlyName = $_.FriendlyName MediaType = [string]$_.MediaType HealthStatus = [string]$_.HealthStatus OperationalStatus = [string]$_.OperationalStatus SizeGB = [math]::Round($_.Size / 1GB, 1) } } $maintenanceInfo.Disks = @($disks) } catch {} # 2d. DISM RestoreHealth try { $dismOut = & DISM.exe /Online /Cleanup-Image /RestoreHealth 2>&1 $maintenanceInfo.DismStatus = if ($LASTEXITCODE -eq 0) { 'OK (0)' } else { "ExitCode $LASTEXITCODE" } } catch { $maintenanceInfo.DismStatus = "Error: $($_.Exception.Message)" } # 2e. SFC /scannow try { $sfcOut = & sfc.exe /scannow 2>&1 $maintenanceInfo.SfcStatus = if ($LASTEXITCODE -eq 0) { 'OK (0)' } else { "ExitCode $LASTEXITCODE" } } catch { $maintenanceInfo.SfcStatus = "Error: $($_.Exception.Message)" } # 2f. Re-trim SSDs try { $ssds = Get-PhysicalDisk -ErrorAction SilentlyContinue | Where-Object { $_.MediaType -eq 'SSD' } if ($ssds) { Optimize-Volume -DriveLetter C -ReTrim -ErrorAction Stop | Out-Null $maintenanceInfo.SsdReTrimmed = 'Trimmed (C:)' } else { $maintenanceInfo.SsdReTrimmed = 'No SSD detected' } } catch { $maintenanceInfo.SsdReTrimmed = "Skipped: $($_.Exception.Message)" } $maintenanceInfo.FreeSpaceAfterGB = Get-FreeGB } # ---- 3. Windows Update Scan & Pending Reboot Check ---- $updateScanTriggered = $false try { $uso = "$env:WINDIR\System32\UsoClient.exe" if (Test-Path $uso) { Start-Process -FilePath $uso -ArgumentList 'StartScan' -NoNewWindow -Wait -ErrorAction Stop $updateScanTriggered = $true } else { $au = New-Object -ComObject Microsoft.Update.AutoUpdate $au.DetectNow() $updateScanTriggered = $true } } catch {} $pendingSources = @() if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') { $pendingSources += 'CBS' } if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') { $pendingSources += 'WindowsUpdate' } try { $pfro = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name 'PendingFileRenameOperations' -ErrorAction SilentlyContinue).PendingFileRenameOperations if ($pfro) { $pendingSources += 'PendingFileRename' } } catch {} $rebootPending = ($pendingSources.Count -gt 0) $rebootScheduled = $false if ($DoReboot -and $rebootPending) { try { & shutdown.exe /r /t 60 /c "Cyber Highway Remote-ServiceAndScan.ps1: Pending reboot detected. Restarting in 60 seconds." $rebootScheduled = $true } catch {} } $durationMin = [math]::Round(((Get-Date) - $runStart).TotalMinutes, 2) $diskHealthSummary = if ($maintenanceInfo.Disks.Count -gt 0) { ($maintenanceInfo.Disks | ForEach-Object { "$($_.FriendlyName): $($_.HealthStatus)" }) -join '; ' } else { 'N/A' } [pscustomobject]@{ ComputerName = $env:COMPUTERNAME Reachable = $true TimestampUtc = (Get-Date).ToUniversalTime().ToString('o') DurationMinutes = $durationMin Defender = $defenderInfo Maintenance = $maintenanceInfo UpdateScanTriggered = $updateScanTriggered PendingReboot = $rebootPending PendingRebootReasons = ($pendingSources -join ', ') RebootTriggered = $rebootScheduled DiskHealthSummary = $diskHealthSummary } } Write-Host '' Write-Host '=====================================================================' -ForegroundColor DarkGreen Write-Host ' Cyber Highway LTD - Remote-ServiceAndScan.ps1 (WinRM)' -ForegroundColor Green Write-Host (" Targets: {0} | ScanType: {1} | Maintenance: {2} | Auto-Reboot: {3}" -f ($ComputerName -join ', '), $ScanType, (-not $SkipMaintenance), [bool]$Reboot) -ForegroundColor Cyan Write-Host '=====================================================================' -ForegroundColor DarkGreen $allReports = New-Object System.Collections.Generic.List[object] foreach ($target in $ComputerName) { Write-Host ("`n[{0}] Connecting to {1} over WinRM..." -f (Get-Date -Format 'HH:mm:ss'), $target) -ForegroundColor Cyan $icmParams = @{ ComputerName = $target ScriptBlock = $remoteBlock ArgumentList = @($ScanType, (-not $SkipMaintenance.IsPresent), $Reboot.IsPresent, $TempFileAgeDays) ErrorAction = 'Stop' } if ($Credential) { $icmParams['Credential'] = $Credential } try { $res = Invoke-Command @icmParams $allReports.Add($res) Write-Host ("[{0}] Completed on {1} in {2} min." -f (Get-Date -Format 'HH:mm:ss'), $target, $res.DurationMinutes) -ForegroundColor Green } catch { Write-Warning ("[{0}] Failed on {1}: {2}" -f (Get-Date -Format 'HH:mm:ss'), $target, $_.Exception.Message) $allReports.Add([pscustomobject]@{ ComputerName = $target Reachable = $false TimestampUtc = (Get-Date).ToUniversalTime().ToString('o') DurationMinutes = 0.0 Error = $_.Exception.Message Defender = [pscustomobject]@{ ScanType = $ScanType; ScanCompleted = $false; NewDetectionsCount = -1; Detections = @() } Maintenance = [pscustomobject]@{ Skipped = [bool]$SkipMaintenance; FreeSpaceAfterGB = 0.0; DismStatus = 'N/A'; SfcStatus = 'N/A'; SsdReTrimmed = 'N/A' } UpdateScanTriggered = $false PendingReboot = $false RebootTriggered = $false DiskHealthSummary = 'Unreachable' }) } } $stamp = Get-Date -Format 'yyyy-MM-dd_HHmmss' $jsonPath = Join-Path $ReportDir "Remote-ServiceAndScan_$stamp.json" $reportPayload = [ordered]@{ GeneratedBy = 'Cyber Highway LTD - Remote-ServiceAndScan.ps1' GeneratedAtUtc = (Get-Date).ToUniversalTime().ToString('o') Parameters = [ordered]@{ ComputerName = $ComputerName ScanType = $ScanType SkipMaintenance = [bool]$SkipMaintenance Reboot = [bool]$Reboot } Results = $allReports } $reportPayload | ConvertTo-Json -Depth 6 | Set-Content -Path $jsonPath -Encoding UTF8 # Print Summary Table Write-Host '' Write-Host '=== Remote Service & Scan Summary ===' -ForegroundColor Green $summaryRows = foreach ($r in $allReports) { [pscustomobject]@{ ComputerName = $r.ComputerName Reachable = $r.Reachable ScanType = $r.Defender.ScanType Threats = $r.Defender.NewDetectionsCount FreeGB = $r.Maintenance.FreeSpaceAfterGB DiskHealth = $r.DiskHealthSummary DISM = $r.Maintenance.DismStatus SFC = $r.Maintenance.SfcStatus PendingReboot = $r.PendingReboot Rebooting60s = $r.RebootTriggered Mins = $r.DurationMinutes } } $summaryRows | Format-Table -AutoSize Write-Host ("JSON report saved to: {0}" -f $jsonPath) -ForegroundColor Cyan if ($allReports | Where-Object { $_.Defender.NewDetectionsCount -gt 0 }) { Write-Warning 'One or more targets reported Defender detections! Review the JSON report before assuming threats are cleaned.' }