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 ?
>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)