4

Although there is a VERY similar question : How to lock my computer after a certain amount of time from login? I don't think that it is suiting my needs. I need my computer to lock NOT SHUTDOWN.

What I did: Made a bat file with following script

shutdown -l /t 1800

When I put up a task in Task Scheduler it just simply didn't LOCK my PC. The bat file itself doesn't work. I have no idea why.

If I do.

shutdown -l

It works perfectly. But I don't want this to happen. I want it to do this after a specific amount of time.

I do understand that WinKey + L and Signing Out is different.

Also is there a way to do this every day except on Saturdays and Sundays, I have to work during this time.

4 Answers4

3

Refer to this old vbscript Auto-Lock_On_Idle_TimeOut.vbs


I changed it a little in order to run in loop and for every 30 minutes the computer will be locked.


Auto-Lock_After_Amount_of_Time_Defined_by_User.vbs

'#################################################################################
'#       Script Name : Auto-Lock_After_Amount_of_Time_Defined_by_User.vbs        #
'#################################################################################
Option Explicit
Dim Copyright,Msg
Dim Timeout,strCommand,VbsPath,ShortcutName
Timeout = 30 '30 minutes : You can modify this variable as your convenience
Msg = Lang
Copyright = Msg(0) & ChrW(169) &" Hackoo 2022"
If AppPrevInstance() Then 
    MsgBox Msg(1) & VbCrLF & CommandLineLike(WScript.ScriptName),VbExclamation,Copyright
    WScript.Quit
Else 
    Do
        strCommand = "CMD /C Shutdown -L"
        VbsPath = Wscript.ScriptFullName
        ShortcutName = "Auto-Lock_TimeOut"
        Call Shortcut(VbsPath,ShortcutName)
        Wscript.Sleep 1000 * 60 * Timeout
        CreateObject("Wscript.Shell").Run strCommand,0,True
    Loop
End If
'---------------------------------------------------------------------------------------------------------------
Sub Shortcut(PathApplication,ShortcutName)
    Dim objShell,StartFolder,objShortCut,MyTab
    Set objShell = CreateObject("WScript.Shell")
    MyTab = Split(PathApplication,"\")
    If ShortcutName = "" Then
        ShortcutName = MyTab(UBound(MyTab))
    End if
    StartFolder = objShell.SpecialFolders("Startup")
    Set objShortCut = objShell.CreateShortcut(StartFolder & "\" & ShortcutName & ".lnk")
    objShortCut.TargetPath = DblQuote(PathApplication)
    ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,44"
    objShortCut.Save
End Sub
'---------------------------------------------------------------------------------------------------------------
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'---------------------------------------------------------------------------------------------------------------
Function AppPrevInstance()   
    With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")   
        With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
            " AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")   
            AppPrevInstance = (.Count > 1)   
        End With   
    End With   
End Function    
'----------------------------------------------------------------------------------------------------------------
Function CommandLineLike(ProcessPath)   
    ProcessPath = Replace(ProcessPath, "\", "\\")   
    CommandLineLike = "'%" & ProcessPath & "%'"   
End Function
'----------------------------------------------------------------------------------------------------------------
Function OSLang()
    Dim dtmConvertedDate,strComputer,objWMIService,oss,os
    Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set oss = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
    For Each os in oss
        OSLang = os.OSLanguage
    Next
End Function
'----------------------------------------------------------------------------------------------------------------
Function Lang()
Dim MsgFR,MsgEN

MsgFR = Array("Verrouillage automatique en cas d'inactivité " ,"ATTENTION ! Il y a une autre instance en cours d'exécution !",_ "Attention ! Votre Session va être verrouillé dans 20 secondes !nn Voulez-vous confirmer le Verrouillage de votre session ?","nn OUI ou NON ?")

MsgEN = Array("Automatic Lock Session On Idle TimeOut ","ATTENTION ! There is another instance running !",_ "Warning ! Your Session will be locked in 20 seconds !nn Do you want to confirm the Locking of your session ?","nn YES or NO ?")

'Vérifiez si le système est français pour définir le tableau français comme message, sinon définissez-le comme anglais 'Check if the system is french to set the French array as message otherwise set it as English

If Oslang = 1036 Then Lang = MsgFR ' French Array Message to be set Else Lang = MsgEN ' English Array Message to be set End If End Function '----------------------------------------------------------------------------------------------------------------

Hackoo
  • 1,410
2
  1. Run Task Scheduler.
  2. Create a scheduled task which is activated given amount of time after logon - on Trigger tab, there is a trigger for logon and option to delay action after the event - here you enter your time.
  3. Check Run with highest privileges (especially if locking does not work without this option).
  4. Put your BAT file as runnable action.

Done.

You cannot add an exception for weekends into the UI, but you can test for weekday directly in your batch file or ps1 file. Or test for existence of file "do-not-lock". If it is present, end your batch without locking. Create/delete that file using scheduled tasks (which run on weekday/weekend).

miroxlav
  • 14,845
2

Just copy paste this into your bat instead:

call timeout /t 1800 && Rundll32.exe user32.dll,LockWorkStation

And if you want your bat to run silently follow this guide before adding it to Task Scheduler

Mastaxx
  • 1,379
1

Thank you for all your responses, each one of you gave me a piece to work with. Here is the completed answer:

$i = 0
$sTime = 0;
$day = (Get-Date).DayOfWeek

if ($day -match "Saturday|Sunday") { $sTime = 6000 } else { <#Whatever you need to do#> }

Write-Host "Screen time allocation on a $day : $sTime"

while($i -ne $sTime) { $remainSTime = $sTime - $i $ts = [timespan]::fromseconds($remainSTime) Write-Host $ts Start-Sleep -Seconds 1 $i++ } Rundll32.exe user32.dll,LockWorkStation

That is the complete answer. @Hackoo answer was good but the vbs script was incredibly verbose and hard to understand. As a user concerned about security I decided to just try and understand the script :)