Search code examples
powershellcommand-prompt

PowerShell Open Close Browser Randomly


How Do I Open and close chrome browser randomly in an infinite loop basically I need a script to open 3 URLs on randomly the whole night.

$URLs = @(
'http://site.tld/url1'
'http://site.tld/url2'
'http://site.tld/url3'
)

$minSeconds = 10 * 60
$maxSeconds = 15 * 600

# Loop forever
while($true){
# Send requests to all 3 urls
$URLs |ForEach-Object {
Invoke-WebRequest -Uri $_
}

# Sleep for a random duration between 10 and 15 minutes
Start-Sleep -Seconds (Get-Random -Min $minSeconds -Max $maxSeconds)
}

Solution

  • Invoke-* does not open a browser. You use those to interact with web site info without the need for a browser. You'd want to use Start-Process, which will open the default browser. You can of course instead start Chrome.

    $URLs = @(
    'http://site.tld/url1'
    'http://site.tld/url2'
    'http://site.tld/url3'
    )
    
    $minSeconds = 10 * 60
    $maxSeconds = 15 * 600
    
    # Loop forever
    while($true)
    {
        # Send requests to all 3 urls
        $URLs | ForEach-Object {Start-Process $PSitem}
    
        # Sleep for a random duration between 10 and 15 minutes
        Start-Sleep -Seconds (Get-Random -Min $minSeconds -Max $maxSeconds)
    }
    

    After that sleep line, you need to add code to close the browser.

    $URLs | 
    ForEach-Object {Start-Process -FilePath chrome.exe -ArgumentList $PSitem}
    
    Stop-Process -Name chrome -Force