簡體   English   中英

Powershell 重啟控制台問題

[英]Powershell reboot console issue

我有一個登錄腳本,如果 PC 的運行時間超過允許的時間,它會重新啟動 PC。

我有一個 PowerShell 腳本,它在登錄期間運行並每周執行一次,以檢查機器的正常運行時間並在超過 48 小時時重新啟動。 該腳本允許用戶請求擴展,這樣他們就不會立即被踢出機器。 我有 1、3、8 小時的延期。 只有1、3小時的延期工作。 看起來如果你輸入一個大於 3 的值,它不接受它。 有沒有辦法讓這個“擴展”工作超過 3 小時?

<#
.SYNOPSIS
    Script displays an interactive popup that display the reason for having the reboot the computer.
.DESCRIPTION
     The reboot script gives users the option to reboot now or delay the reboot for 1, 3, or 6 hours
.EXAMPLE
    Script executes from the login script
.INPUTS
    N/A
.OUTPUTS
    N/A
.NOTES
    General notes
#>

try {
    Add-Type -AssemblyName PresentationCore, PresentationFramework, WindowsBase, system.windows.forms
} 
catch {}

#Calculate the time since last reboot

$lastBootTime = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object LastBootUpTime | ForEach-Object { Get-Date -Date $_.LastBootUpTime }
$Time = (Get-Date) - $lastBootTime

#if last reboot is less than 2 days exit the script.
if ($Time.TotalHours -lt 48) {
    exit
}

#if computer has a server os, exit
$version = (Get-CimInstance -ClassName Win32_OperatingSystem).caption

if($version -match "server")
{
    exit
}

<#
 # Set Sync hash
 #>
$Global:hash = [hashtable]::Synchronized(@{})
$Global:hash.Stopwatch = New-Object System.Diagnostics.Stopwatch
$Global:hash.Timer = New-Object System.Windows.Forms.Timer
$Global:hash.Timer.Enabled = $true
$Global:hash.Timer.Interval = 1000


<#
 # Form design XML
 #>
[xml]$xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="window" Height="340" Width="400" Title="Mandatory Reboot"  WindowStartupLocation="CenterScreen" Background="Transparent" AllowsTransparency="True"
ResizeMode="NoResize" ShowInTaskbar="True"  SizeToContent="Height" Topmost="True" WindowStyle="None">
    <Window.Resources>
        <SolidColorBrush x:Key="Brush_ChromeBackground" Color="#FFC8D1E0"/>
        <SolidColorBrush x:Key="Brush_ChromeBorder" Color="#FFA0A0A0"/>
    </Window.Resources>
    <Border x:Name="Border_Chrome"  BorderBrush="{StaticResource Brush_ChromeBorder}" BorderThickness="5"  CornerRadius="10"  Width="Auto" Background="#FFCD3232">
        <Grid Margin="15" >
            <Grid.RowDefinitions>
                <RowDefinition Height="120"></RowDefinition>
                <RowDefinition Height="60"></RowDefinition>
                <RowDefinition Height="60"></RowDefinition>
                <RowDefinition Height="60"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="50"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBlock TextWrapping="Wrap" Grid.Column="0" Grid.ColumnSpan="3" FontSize="14" Foreground="White">
                <Bold FontSize="16">Mandatory Reboot</Bold><LineBreak/>
                This computer exceeds the maximum allowed uptime. Your computer will be automatically rebooted unless manually restarted or an extension is requested.<LineBreak/>
            </TextBlock>
            <Button Name="RestartNowBtn" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="3" Width="240" Height="40" HorizontalContentAlignment="Center" HorizontalAlignment="Left">
                <StackPanel Orientation="Horizontal" >
                    <Label Content="Restart Now" FontWeight="Bold"></Label>
                </StackPanel>
            </Button>
            <StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Margin="5,8" >
                <GroupBox Width="100" Header="Postpone">
                    <ComboBox Name="ScheduleValue" VerticalAlignment="Center" >
                        <ComboBoxItem Name="one" Selector.IsSelected="True">1</ComboBoxItem>
                        <ComboBoxItem Name="three">3</ComboBoxItem>
                        <ComboBoxItem Name="eight">8</ComboBoxItem>
                    </ComboBox>
                </GroupBox>
                <TextBlock Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" FontWeight="Bold">Hour(s)</TextBlock>
                <Button Content="Request Extension" Name="scheduleBtn" Width="110" FontWeight="Bold"></Button>
            </StackPanel>
            <Grid Grid.Row="3" Grid.ColumnSpan="3" Margin="10">
                <ProgressBar Name="Time" Maximum="100" Value="100"></ProgressBar>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Time to Automatic Reboot (All unsaved work will be lost)</TextBlock>
            </Grid>
        </Grid>
    </Border>
</Window>
'@

$Global:hash.window = [Windows.Markup.XamlReader]::Load((New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $xaml))

#Connect to Control
$xaml.SelectNodes("//*[@Name]") | ForEach-Object -Process { 
    $Global:hash.$($_.Name) = $Global:hash.window.FindName($_.Name)
}

<#
 # Restart Now Button Even Handler
 #>
$Global:hash.RestartNowBtn.Add_Click( {
        #Stop the timer so that the auto reboot dosen't happen
        $Global:hash.Timer.Stop()
        #Force Reboot Now!
        cmd.exe /c shutdown.exe -r -d P:0:0 -t 60 -f
        $Global:hash.window.Close()
    })

<#
 # Schedule Button Click event handler
 #>
$Global:hash.ScheduleBtn.Add_Click( {

        switch ($Global:hash.ScheduleValue.SelectedItem.Name) {
            "one" {
                $rebootTime = (Get-Date).AddHours(1).TimeOfDay.TotalSeconds
            }
            "three" {
                $rebootTime = (Get-Date).AddHours(3).TimeOfDay.TotalSeconds
            }
            "eight" {
                $rebootTime = (Get-Date).AddHours(8).TimeOfDay.TotalSeconds
            }
        }

        $startTime = [Math]::Round(($rebootTime - (Get-Date).TimeOfDay.TotalSeconds), 0)

        #Stop the timer so that the auto reboot dosen't happen
        $Global:hash.Timer.Stop()

        cmd.exe /c shutdown.exe -r -d P:0:0 -t $startTime -f 

        $Global:hash.Window.Close()
    })

<#
 # Form Loaded Event Handler
 #>
$Global:hash.window.Add_Loaded( {

        $Global:hash.Stopwatch.Start()
        $Global:hash.Timer.Add_Tick( {
                [timespan]$secs = $Global:hash.Stopwatch.Elapsed

                if ($secs.TotalSeconds -gt 120) {
                    cmd.exe /c shutdown.exe -r -d P:0:0 -t 60 -f
                    $Global:hash.Timer.Stop()
                    $Global:hash.window.Close()
                    exit
                }

                $Global:hash.Time.Value = (100 - (($secs.TotalSeconds / 120) * 100))
            })

        $Global:hash.Timer.Start()
    })

<#
 # Start the form
 #>
$Global:hash.window.ShowDialog() | Out-Null

我想允許延長 8 小時,但不允許超過 3 小時。

這是 shutdown.exe可執行文件的限制。 根據此處找到的文檔:

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/shutdown

 
 
 
  
  /t <XXX> Sets the time-out period or delay to XXX seconds before a restart or shutdown. This causes a warning to display on the local console. You can specify 0-600 seconds. If you do not use /t, the time-out period is 30 seconds by default.
 
 

如果你想超越它,你必須在執行 shutdown.exe之前在 PowerShell 中創建一個暫停。 這可以通過在 8 小時選項中添加 start-sleep 、睡眠 3 小時,然后指定最大 600 秒計時器來完成。

編輯:看起來那個文檔已經過時了,關機現在可以接受長達 10 年的任何內容(以秒為單位格式化)。 看,shutdown 命令只需要幾秒鍾。 你應該能夠用秒 x 分鍾 x 小時來計算它,而不是你正在嘗試的所有花哨的數學。 一分鍾 60 秒,一小時 60 分鍾,所以唯一改變的是延遲的小時數。 嘗試這個:

 $Global:hash.ScheduleBtn.Add_Click( { $startTime = switch ($Global:hash.ScheduleValue.SelectedItem.Name) { "one" { 1*60*60 } "three" { 3*60*60 } "eight" { 8*60*60} } $Global:hash.Timer.Stop() cmd.exe /c shutdown.exe -r -d P:0:0 -t $startTime -f $Global:hash.Window.Close() }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM