@echo off :: ============================================================================ :: Remote-ServiceAndScan.bat - Single-File Interactive Launcher :: Published by Cyber Highway LTD (https://www.cyberhighway.co.uk) :: Bedfordshire | 07378 510 974 | info@cyberhighway.co.uk :: :: Double-click to run. Automatically requests Administrator privileges, :: prompts interactively for targets and options, and saves JSON reports :: to a "Reports" folder next to this file. :: ============================================================================ setlocal set "SELF=%~f0" set "WORKDIR=%~dp0" powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^ "$c = Get-Content -LiteralPath $env:SELF -Raw; $i = $c.LastIndexOf('<# :POWERSHELL_PAYLOAD #>'); if ($i -lt 0) { Write-Error 'Payload not found'; exit 1 }; $ps = $c.Substring($i); Invoke-Expression $ps" exit /b %ERRORLEVEL% <# :POWERSHELL_PAYLOAD #> $ErrorActionPreference = 'Continue' $batchPath = $env:SELF $batchDir = if ($env:WORKDIR) { $env:WORKDIR.TrimEnd('\') } else { (Get-Location).Path } # Self-elevate as Administrator if not already elevated $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host 'Relaunching as Administrator...' -ForegroundColor Yellow Start-Process -FilePath 'cmd.exe' -ArgumentList "/c `"`"$batchPath`"`"" -Verb RunAs exit } Clear-Host Write-Host '=====================================================================' -ForegroundColor DarkGreen Write-Host ' Cyber Highway LTD - Remote-ServiceAndScan Interactive Launcher' -ForegroundColor Green Write-Host ' Single-File WinRM Malware Scan & Maintenance Utility' -ForegroundColor Cyan Write-Host '=====================================================================' -ForegroundColor DarkGreen Write-Host '' # 1. Target PC name(s) or IP do { $rawTargets = Read-Host '1. Enter target PC name(s) or IP address(es) (comma-separated, e.g. PC01,PC02)' $rawTargets = $rawTargets.Trim() } while ([string]::IsNullOrWhiteSpace($rawTargets)) $ComputerName = $rawTargets -split '[,\s]+' | Where-Object { $_ -match '^[A-Za-z0-9._\-]+$' } if (-not $ComputerName -or $ComputerName.Count -eq 0) { Write-Warning 'No valid hostnames or IP addresses entered. Exiting.' Read-Host 'Press Enter to close' exit 1 } # 2. Quick or Full scan $scanInput = Read-Host '2. Scan type - [Q]uick or [F]ull? (Default: Quick)' $ScanType = if ($scanInput.Trim() -match '^(F|Full)$') { 'Full' } else { 'Quick' } # 3. Whether to run maintenance $maintInput = Read-Host '3. Run maintenance (temp files, Recycle Bin, disk health, DISM, SFC, SSD trim)? [Y/N] (Default: Y)' $SkipMaintenance = ($maintInput.Trim() -match '^(N|No)$') # 4. Whether to reboot if one is pending $rebootInput = Read-Host '4. Restart target automatically (60s delay) if a pending reboot is detected? [Y/N] (Default: N)' $Reboot = ($rebootInput.Trim() -match '^(Y|Yes)$') # 5. Whether to use different credentials $credInput = Read-Host '5. Use different credentials (Get-Credential) for remote connection? [Y/N] (Default: N)' $Credential = $null if ($credInput.Trim() -match '^(Y|Yes)$') { $Credential = Get-Credential } $ReportDir = Join-Path $batchDir '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 $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)" } $mpAfter = Get-MpComputerStatus -ErrorAction SilentlyContinue if ($mpAfter) { $defenderInfo.SignatureVersion = $mpAfter.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 } $maintenanceInfo = [ordered]@{ Skipped = (-not $DoMaintenance) TempFilesFreedMB = 0.0 RecycleBinCleared = $false FreeSpaceBeforeGB = $freeBeforeGB FreeSpaceAfterGB = $freeBeforeGB Disks = @() DismStatus = 'Skipped' SfcStatus = 'Skipped' SsdReTrimmed = 'Skipped' } if ($DoMaintenance) { $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) try { Clear-RecycleBin -Force -ErrorAction Stop; $maintenanceInfo.RecycleBinCleared = $true } catch {} 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 {} try { & DISM.exe /Online /Cleanup-Image /RestoreHealth 2>&1 | Out-Null $maintenanceInfo.DismStatus = if ($LASTEXITCODE -eq 0) { 'OK (0)' } else { "ExitCode $LASTEXITCODE" } } catch { $maintenanceInfo.DismStatus = "Error: $($_.Exception.Message)" } try { & sfc.exe /scannow 2>&1 | Out-Null $maintenanceInfo.SfcStatus = if ($LASTEXITCODE -eq 0) { 'OK (0)' } else { "ExitCode $LASTEXITCODE" } } catch { $maintenanceInfo.SfcStatus = "Error: $($_.Exception.Message)" } 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 } $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 { (New-Object -ComObject Microsoft.Update.AutoUpdate).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: 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 RebootTriggered = $rebootScheduled DiskHealthSummary = $diskHealthSummary } } $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), $Reboot, 7) 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" [ordered]@{ GeneratedBy = 'Cyber Highway LTD - Remote-ServiceAndScan.bat' GeneratedAtUtc = (Get-Date).ToUniversalTime().ToString('o') Results = $allReports } | ConvertTo-Json -Depth 6 | Set-Content -Path $jsonPath -Encoding UTF8 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 Write-Host '' Read-Host 'Done. Press Enter to close'