Public/Invoke-SystemMaintenance.ps1

<#
.SYNOPSIS
    Performs a series of system maintenance tasks including service management, disk cleanup, defragmentation, and system updates.
 
.DESCRIPTION
    This function orchestrates a series of system maintenance operations including starting and stopping services,
    cleaning up the disk, defragmenting the disk, clearing event logs, managing scheduled tasks, and updating group policies.
    It concludes with setting the execution policy to restricted and scheduling a shutdown.
 
.EXAMPLE
    Invoke-SystemMaintenance
    Runs the complete set of maintenance tasks sequentially.
 
.NOTES
    Requires administrative privileges for most operations.
#>


function Invoke-SystemMaintenance {
    [CmdletBinding()]
    param ()

    # Function to display status messages
    function Show-Status {
        param (
            [string]$Message
        )
        Write-Host $Message -ForegroundColor Green
    }

    # Ensure script is running as Administrator
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Write-Warning "Please run this script as an Administrator!"
        return
    }

    # Starting necessary services
    Show-Status "Starting necessary services and setting them to automatic startup"
    "bits", "wuauserv", "defragsvc" | ForEach-Object {
        try {
            Show-Status "Starting $_ service and setting it to automatic startup"
            Get-Service -Name $_ | Set-Service -StartupType Automatic -PassThru | Start-Service
        } catch {
            Write-Host "Failed to start $_ service" -ForegroundColor Red
        }
    }

    # Removing directories
    Show-Status "Removing temporary directories"
    "C:\Temp\*", "C:\Windows\Build\*", "C:\Users\Admin\Desktop\*" | ForEach-Object {
        try {
            Remove-Item $_ -Force -Recurse -ErrorAction SilentlyContinue
            Show-Status "Removed $_"
        } catch {
            Write-Host "Failed to remove $_" -ForegroundColor Red
        }
    }

    # Disk Cleanup
    Show-Status "Running Disk Cleanup"
    try {
        $volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
        foreach ($key in $volumeCaches) {
            New-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0099 -Value 2 -Type DWORD -Force
        }
        Start-Process "$env:SystemRoot\System32\cleanmgr.exe" -ArgumentList "/sagerun:99" -Wait
        $volumeCaches | ForEach-Object {
            Remove-ItemProperty -Path "$($_.PSPath)" -Name StateFlags0099 -Force
        }
        Show-Status "Disk Cleanup completed"
    } catch {
        Write-Host "Disk Cleanup failed" -ForegroundColor Red
    }

    # Disk Defragmentation
    Show-Status "Running Disk Defragmentation"
    try {
        Start-Process "defrag.exe" -ArgumentList "C: /H /V" -Wait
        Show-Status "Disk Defragmentation completed"
    } catch {
        Write-Host "Disk Defragmentation failed" -ForegroundColor Red
    }

    # Clearing Event Logs
    Show-Status "Clearing Event Logs"
    try {
        Get-WinEvent -ListLog * -Force | ForEach-Object {
            Wevtutil.exe cl $_.LogName
        }
        Show-Status "Event Logs cleared"
    } catch {
        Write-Host "Clearing Event Logs failed" -ForegroundColor Red
    }

    # Stopping services and setting them to disabled
    Show-Status "Stopping services and setting them to disabled startup"
    "bits", "wuauserv", "defragsvc" | ForEach-Object {
        try {
            Show-Status "Stopping $_ service and setting it to disabled startup"
            Get-Service -Name $_ | Stop-Service -PassThru | Set-Service -StartupType Disabled
        } catch {
            Write-Host "Failed to stop $_ service" -ForegroundColor Red
        }
    }

    # Deleting Scheduled Task
    Show-Status "Deleting Scheduled Task if it exists"
    try {
        $taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like "GpUpdate"}
        if ($taskExists) {
            schtasks /delete /tn "GpUpdate" /f
            Show-Status "Scheduled Task deleted"
        } else {
            Show-Status "Scheduled Task does not exist"
        }
    } catch {
        Write-Host "Deleting Scheduled Task failed" -ForegroundColor Red
    }

    # Set Execution Policy to Restricted
    Show-Status "Setting Execution Policy to Restricted"
    try {
        Set-ExecutionPolicy Restricted -Force
        Show-Status "Execution Policy set to Restricted"
    } catch {
        Write-Host "Setting Execution Policy to Restricted failed" -ForegroundColor Red
    }

    # Run gpupdate and schedule a system shutdown
    Show-Status "Running GPUpdate and scheduling shutdown"
    try {
        gpupdate /force
        Show-Status "GPUpdate completed"
        shutdown /s /t 5
    } catch {
        Write-Host "GPUpdate or shutdown scheduling failed" -ForegroundColor Red
    }
}