Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i run a powershell script continually for 15min?

I have a powershell script that connects to a database as follows:

try
{
# This is a simple user/pass connection string.
# Feel free to substitute "Integrated Security=True" for system logins.
$connString = "Data Source=YourInstance;Database=YourDB;User 
 ID=YourUser;Password=YourPassword"

 #Create a SQL connection object
 $conn = New-Object System.Data.SqlClient.SqlConnection $connString

 #Attempt to open the connection
 $conn.Open()
 if($conn.State -eq "Open")
 {
    # We have a successful connection here
    # Notify of successful connection
    Write-Host "Test connection successful"
    $conn.Close()
}
# We could not connect here
 # Notify connection was not in the "open" state
}

catch
{
    # We could not connect here
    # Notify there was an error connecting to the database
}

Now is there a way that i can continually run this script for 15min or 30min with a
20sec delay in between each run ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a do loop with the condition to break it when the elapsed time of a StopWatch is greater than 15 minutes. For the 20 second intervals you can use Start-Sleep.

$runtime = [timespan]::FromMinutes(15)
$timer = [System.Diagnostics.Stopwatch]::StartNew()

do {
    try {
        $connString = 'Data Source=YourInstance;....'
        $conn = New-Object System.Data.SqlClient.SqlConnection $connString
        $conn.Open()
        if ($conn.State -eq 'Open') {
            Write-Host 'Test connection successful'
            $conn.Close()
        }
    }
    catch {
        # We could not connect here
        # Notify there was an error connecting to the database
    }

    Start-Sleep -Seconds 20
}
while($runtime -ge $timer.Elapsed)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading