PowerShell重启提示脚本问题求助:强制重启失效+窗口隐藏+语法错误
PowerShell重启提示脚本错误修复及优化
错误原因
你遇到的Get-Date : Cannot bind parameter 'Date'错误,是因为将两个PowerShell语句写在同一行却未添加分隔符:
$TimeNow = Get-Date if ($TimeNow -ge $TimeEnd) { ... }
PowerShell会把if当成Get-Date的参数传入,而if无法转换为DateTime类型,直接触发类型转换错误。同时原脚本存在逻辑缺陷:到达到期时间后仅执行Exit,未触发强制重启,不符合你"60分钟到期后强制重启"的需求。
修复后的完整脚本
以下是修正语法错误、优化逻辑后的脚本,同时解决了到期不执行强制重启的问题:
# 一次性加载所需程序集,避免重复加载 Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName Microsoft.VisualBasic $TimeStart = Get-Date $TimeEnd = $TimeStart.AddMinutes(60) $hasInitiatedForceReboot = $false Do { $TimeNow = Get-Date if ($TimeNow -ge $TimeEnd -and -not $hasInitiatedForceReboot) { # 清理已注册的事件资源 Unregister-Event -SourceIdentifier click_event -ErrorAction SilentlyContinue Remove-Event click_event -ErrorAction SilentlyContinue # 触发10分钟后强制重启 shutdown -r -f -t 600 -c "已达重启延迟上限,请保存工作,电脑将在10分钟后自动重启。" $hasInitiatedForceReboot = $true Exit } else { $Balloon = New-Object System.Windows.Forms.NotifyIcon $Balloon.Icon = [System.Drawing.SystemIcons]::Information $Balloon.BalloonTipText = "IT部门要求重启电脑以维护系统稳定性和安全,请尽快重启。" $Balloon.BalloonTipTitle = "需重启系统" $Balloon.BalloonTipIcon = "Warning" $Balloon.Visible = $true # 显示通知气泡20秒 $Balloon.ShowBalloonTip(20000) # 注册气泡点击事件 Unregister-Event -SourceIdentifier click_event -ErrorAction SilentlyContinue Register-ObjectEvent $Balloon BalloonTipClicked -SourceIdentifier click_event -Action { $choice = [Microsoft.VisualBasic.Interaction]::MsgBox('是否立即重启电脑?', 'YesNo,MsgBoxSetForeground,Question', '系统维护') if ($choice -eq "Yes") { shutdown -r -f } } | Out-Null # 等待10分钟(600秒)或用户点击事件 Wait-Event -Timeout 600 -SourceIdentifier click_event | Out-Null # 清理资源 Unregister-Event -SourceIdentifier click_event -ErrorAction SilentlyContinue $Balloon.Dispose() } } Until ($TimeNow -ge $TimeEnd)
隐藏PowerShell窗口的方法
要让脚本运行时不显示PowerShell窗口,有两种实用方法:
- 命令行参数启动:
使用以下命令运行脚本,-WindowStyle Hidden参数会直接隐藏窗口:powershell.exe -WindowStyle Hidden -File "C:\scripts\Reboot_Toast.ps1" - VBScript包装:
创建一个.vbs文件(例如RunRebootScript.vbs),写入以下内容后双击运行:Set objShell = CreateObject("Wscript.Shell") objShell.Run "powershell.exe -WindowStyle Hidden -File ""C:\scripts\Reboot_Toast.ps1""", 0, False
内容的提问来源于stack exchange,提问作者sbdave805
相关产品推荐
相关产品推荐

