Windows Task for restart if user not logged in

僤鯓⒐⒋嵵緔 提交于 2019-12-11 15:06:23

问题


I'm trying to create scheduled task for Windows reboot, which is executed if any user is not logged in. If user is logged in locally or over RDP, the machine should not be restarted.

For unconditional restart, I have task in Task Scheduler with: Action: "Start a program", Program/script: "powershell", Add arguments: "restart-computer -force"

For conditional restart I have powershell code:

$ErrorActionPreference = "Continue"
$userstatus = quser /server:'localhost'
if(!$userstatus){
    Restart-Computer -Force
    }
else{
    exit
    }

I can get the conditional restart working fine when I save the script as .ps1 file and add the filepath to the schedule as argument. I need the conditional restart with several desktops and I would like to avoid saving the .ps1 file locally for each machine. Is it possible to pass the entire script as argument?


回答1:


Your logic's a bit off. If you plan on creating the scheduled task for each PC, it should look something like this:

$Users = quser.exe
If ($Users -match 'No\sUser') { Restart-Computer -Force }

From here, because of the syntax, you should encode it, then you could utilize schtasks.exe to create your task:

[Convert]::ToBase64String(
    [Text.Encoding]::Unicode.GetBytes(
        "If(@(quser.exe) -match 'no\suser'){Restart-Computer -Force}"
    )
)

Output:

SQBmACAAKABAACgAcQB1AHMAZQByAC4AZQB4AGUAKQAgAC0AbQBhAHQAYwBoACAAJwBuAG8AXABzAHUAcwBlAHIAJwApAHsAUgBlAHMAdABhAHIAdAAtAEMAbwBtAHAAdQB0AGUAcgAgAC0ARgBvAHIAYwBlAH0A

schtasks.exe /Create /TN AutoRestart /SC DAILY /ST 20:00 /RU SYSTEM /TR "powershell.exe -EncodedCommand SQBmACAAKABAACgAcQB1AHMAZQByAC4AZQB4AGUAKQAgAC0AbQBhAHQAYwBoACAAJwBuAG8AXABzAHUAcwBlAHIAJwApAHsAUgBlAHMAdABhAHIAdAAtAEMAbwBtAHAAdQB0AGUAcgAgAC0ARgBvAHIAYwBlAH0A"


来源:https://stackoverflow.com/questions/48428619/windows-task-for-restart-if-user-not-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!