代码之家  ›  专栏  ›  技术社区  ›  Traci

如何连续运行powershell脚本15分钟?

  •  0
  • Traci  · 技术社区  · 3 年前

    我有一个连接到数据库的powershell脚本,如下所示:

    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
    }
    

    现在有没有一种方法可以让我用一个 每次运行之间有20秒的延迟?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Santiago Squarzon    3 年前

    您可以使用 do loop 当 StopWatch 大于15分钟。对于20秒的间隔,您可以使用 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)
    
    推荐文章