Alternative to Thread. Sleep with different hardware

165 Views Asked by At

I am writing a autologin script in Powershell. With main purpose of doing autologon with keystrokes on remote clients in our environment after installation, with the desired AD and password entered.

Works fine on my i9. But most people using Tablets and Elitebooks so using

Thread Sleep

Works bad since i would need to have custom timing on Every hardware, or very high default numbers for lower end clients using my script

Is there any way adding an "wait for row above to completed" Before continuation to next.

2

There are 2 best solutions below

0
Paddingtonbear On BEST ANSWER

I got it all working perfect by calling Windows Timer Resolution using ntdll and adjusting it to be 0.500 (Also working using; WinMM library DLL) Then i switched to using [System.Threading.Thread]::Sleep(1 * 1000) instead of normal Start-Sleep. So now i could get a more precise execution wait timing and this does wonders when heavily relying on accurate timing in milliseconds.

    ´$NtSetTimerResolution = @'
[DllImport("ntdll.dll", SetLastError=true)]
public static extern int NtSetTimerResolution(uint DesiredResolution, bool SetResolution, out uint CurrentResolution );
'@

$NtdllSet = Add-Type -MemberDefinition $NtSetTimerResolution -Name 'NtdllSet' -Namespace 'Win32' -PassThru

$TRCurrent=0
$null = $NtdllSet::NtSetTimerResolution(5000, $true, [ref]$TRCurrent)´

Reference: PowerShell Sleep Duration Accuracy and Windows Timers

0
Sage Pourpre On

I don't have enough on your current code to produce a more accurate answer but the idea, in all cases, remains the same.

You should periodically wake up the thread to check whether or not the machine is in the state you want it in and from there, you either go back to sleep or exit the loop and continue.

The delay is up to you but you want to find a sweet spot to have great performance and reactivity.

Example (based on your description)

$IsLoggedIn = $false
while (! $IsLoggedIn) {
    $IsLoggedIn = 'Custom Logic returning $true if the user is logged in'
    if ($IsLoggedIn) { break }
    Start-Sleep -Milliseconds 100
}

You just need to figure out the thing you want to use as the check to validate the computer is in the correct state you need it in before proceeding further.