2

I have a functioning PowerShell script which registers a timer object and sends a key every couple of minutes.

$wshell = New-Object -ComObject Wscript.Shell    

...

function fctName {
    param([ScriptBlock] $action)

    ...

    Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier Timer.Elapsed -Action $action
}

fctName {

    ...

    $wshell.sendkeys("{ESC}")
}

Within the Windows PowerShell ISE the script works just fine, without any errors. But, I would love to run it from a batch file, in which I wrote only this line:

Powershell.exe -noexit C:\...\ScriptName.ps1

No errors are thrown but it does not do what I want, which is to prevent Windows going idle.

Because I '-noexit' the cmd window, I can easily stop the event with

Unregister-Event -SourceIdentifier Timer.Elapsed

It seems to be working because only typing it twice throws an error.

  • Could it be that my batch file needs different code? Maybe "echo" etc. I'm not very familiar with it
  • Could it be that I have to import a module in Powershell?
1
  • I think the problem is that scheduled tasks living in a different session/context respect to the one of the logged user. SendKeys aren't send in the actual user session. Commented Apr 10, 2013 at 14:44

1 Answer 1

1

I'm not that comfortable with PowerShell, but in JScript you could use this code:

var osh = new ActiveXObject("WScript.Shell")
WSH.Echo(
    /cscript/i.test(WSH.FullName)
    ? 'Anti-idle running. Hit Ctrl-C to exit'
    : "Anti-idle running.\nTo stop, use task manager to kill wscript.exe"
);
while (1) {
    WSH.Sleep(120 * 1000);
    osh.SendKeys("{SCROLLLOCK}{SCROLLLOCK}");
}

Save that with a .js extension and you can double-click it to launch it, or launch it from a cmd console via cscript /nologo scriptfile.js.

I think toggling Scroll Lock is more benign than sending Esc, as Esc could have unwanted consequences depending on what application happens to have focus when the SendKeys line fires.


Does PowerShell have access to Windows Script Host methods like Sleep? Apparently so with Start-Sleep. That might be preferable to spawning a timer. Hopefully if my JScript code isn't suitable natively for your evil purposes, it will at least be suitable as pseudocode for your PowerShell script.

Sign up to request clarification or add additional context in comments.

1 Comment

True story. Works only with SendKeys, such as [System.Windows.Forms.SendKeys]::SendWait("{SCROLLLOCK}{SCROLLLOCK}") and the Start-Sleep function in PowerShell within a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.