Functions/ShutdownTimer.ps1


function ShutdownTimer {

    [CmdletBinding()]


    param (
        [parameter()] [int] $Time = 3,
        [Parameter()] [string] [ValidateSet("Seconds", "Minutes", "Hours")] $HMS = "Seconds",
        [parameter()] [string] $At,
        [parameter()] [switch] $Restart,
        [parameter()] [switch] $Lock
    )


    switch ($HMS) {
        "Hours" {
            $Seconds = ($time * 60 * 60)
        }
        "Minutes" {
            $Seconds = ($time * 60)
        }
        "Seconds" {
            $Seconds = $time
        }
    }





    if ($At) {

        if ($At.Length -eq 3) {
            # $At

            $At = "0$($At)"
            $At

        } elseif ($At.Length -eq 4) {

        } else {
            Write-Error "`"At`" not in correct format"
        }

        $ShutdownHour = $At[0] + $At[1]
        $ShutdownHour = [int]$ShutdownHour
        # $ShutdownHour

        $ShutdownMinute = $At[2] + $At[3]
        $ShutdownMinute = [int]$ShutdownMinute
        # $ShutdownMinute

        if ($ShutdownHour -gt 23 -or $ShutdownMinute -gt 59) {
            Write-Error "Time input not correct"
            break
        }

        $EndTime = Get-Date -Hour $ShutdownHour -Minute $ShutdownMinute -Second 00

        if ($EndTime -lt (Get-Date)) {
            $EndTime = $EndTime.AddDays(1)
        }

    } else {
        $EndTime = (Get-Date).AddSeconds($Seconds)
    }


    $i = 0

    while (($TimeRemaining = ($EndTime - (Get-Date))) -gt 0) {

        if (($EndTime - (Get-Date)).TotalSeconds -lt 5) {
            Stop-ProcessSoft msedge -Silent
            Stop-ProcessSoft -ProcessName chrome -Silent
            Stop-ProcessSoft -ProcessName EXCEL -Silent
        }

        if ($Restart) {
            $ActivityText = "Restarting in..."
        } else {
            $ActivityText = "Shutting down in..."
        }
        Write-Progress -Activity $ActivityText -Status $EndTime -SecondsRemaining $TimeRemaining.TotalSeconds
        Start-Sleep 1

        $i++
        if ($Lock -and ($i -eq 2)) {
            $Users = (quser) -ireplace '\s{2,}', ',' | ConvertFrom-Csv
            if (($Users | Where-Object Username -Match ">").Sessionname -eq "console") {
                Rundll32.exe user32.dll, LockWorkStation
            } else {
                tsdiscon.exe
            }
        }


    }

    if ($Restart) {
        Restart-Computer -Force
    } else {
        Stop-Computer -Force
    }

}