1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| function Schedule-NonWorkHours { param( [string]$ComputerName = $env:COMPUTERNAME, [ValidateSet('Shutdown', 'Hibernate', 'Sleep')] [string]$Action = 'Sleep', [int]$StartHour = 18, [int]$EndHour = 8, [switch]$WeekendShutdown, [switch]$EnableWakeUp ) try { $taskName = "GreenComputing_$Action" $actionString = switch ($Action) { 'Shutdown' { "shutdown /s /f /t 60" } 'Hibernate' { "rundll32.exe powrprof.dll,SetSuspendState Hibernate" } 'Sleep' { "rundll32.exe powrprof.dll,SetSuspendState Sleep" } } Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name) schtasks /delete /tn $name /f 2>$null } -ArgumentList $taskName Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name, $action, $hour) schtasks /create /tn $name /tr $action /sc weekly /d MON,TUE,WED,THU,FRI /st $('{0:00}' -f $hour):00:00 /f } -ArgumentList $taskName, $actionString, $StartHour if ($WeekendShutdown) { $weekendTaskName = "GreenComputing_Weekend_$Action" Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name) schtasks /delete /tn $name /f 2>$null } -ArgumentList $weekendTaskName Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name, $action) schtasks /create /tn $name /tr $action /sc weekly /d SAT,SUN /st 20:00:00 /f } -ArgumentList $weekendTaskName, $actionString Write-Host "已创建周末$Action任务:$weekendTaskName" } if ($EnableWakeUp) { $wakeTaskName = "GreenComputing_WakeUp" Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name) schtasks /delete /tn $name /f 2>$null } -ArgumentList $wakeTaskName Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($name, $hour) $wakeupAction = 'powercfg -requestsoverride Process System Awaymode' schtasks /create /tn $name /tr $wakeupAction /sc weekly /d MON,TUE,WED,THU,FRI /st $('{0:00}' -f $hour):00:00 /f } -ArgumentList $wakeTaskName, $EndHour Write-Host "已创建唤醒任务:$wakeTaskName" } return [PSCustomObject]@{ ComputerName = $ComputerName ActionScheduled = $Action WorkdaysStartHour = $StartHour WorkdaysEndHour = $EndHour WeekendShutdownEnabled = $WeekendShutdown WakeUpEnabled = $EnableWakeUp } } catch { Write-Host "非工作时间管理设置失败:$_" } }
|