powershellsleepwakeup

Need to run a powershell script every time system wakes up from Sleep


I just finished writing a script with PowerShell and I need it to run every time my system wakes up from sleep or Hibernation. I tried the gpedit.msc -> User Config -> Windows Settings -> Scripts -> Logon but this does not work when my system Wakes up from 'Sleep'... probably because 'Sleep' - > 'Wake -up' is not technically new logon (As a user I am already logged-on).

Either a Sleep-Wake event or Login (User Login) event should trigger my script.

Any ideas on how I can do this?

More Info on what my script does: It checks if internet/network is connected. If yes, it will attempt to run the Cisco VPN connection command line utility with required arguments and logs me into VPN. Every time I wake my system up from sleep and login I need the damn VPN to connect me automatically.


Solution

  • I figured it out. I used the Task Scheduler as Richard indicated above.

    I set the Trigger as.. On an Event -> System -> Kernel-Power -> 42

    If anyone is interested... here is the script (I am a beginner with PowerShell scripts, so welcome your inputs)

    $strComputerName = gc env:computername
    $strVPN = 'c:\Program Files (x86)\Cisco Systems\VPN Client\vpnclient.exe'
    $vpnArgs = 'connect', 'ProfileName', 'user', 'XXXXXXXX', 'pwd', 'XXXXXXXXXX'
    [int]$count = 6
    Write-Host "Checking for Internet Connectivity"
    While (!([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet))
    {
        Write-Host "Sleeping for 10 seconds before checking for internet again"
        Start-Sleep -s 10
        $count--
        if ( $count -eq 0) 
        {
            Write-Host "Breaking from loop"
            break
        }
    }
    if ( $count -ne 0) { Invoke-Command -ScriptBlock { & $strVPN $vpnArgs } }
    else { Write-Host "No Internet Connectivity, so not attempting VPN connection" }