简体   繁体   中英

Running a command in a loop to keep a connection open

I have written a GUI that connects to Exchange Online to automate some tasks. If I leave the GUI inactive for 15 minutes, the connection is closed and I have to restart the GUI to connect again.

How can I include a command that will loop something like "Get-Mailbox -Identity someone@mywebsite.com" every 10 minutes to ensure the connection does hit the idle limit?

I don't think Start-Sleep or Start-Job cmdlets will work as they prevent my GUI from opening until I exit the loop.

Use the following, which assumes a WinForms application and that your form is stored in variable $form :

# Show the form *non*-modally, by using `.Show()` rather than `.ShowDialog()`
# That is, this statement is *not* blocking and execution continues below.
$form.Show()

# Assume that the connection has just been established.
$lastRefresh = [datetime]::UtcNow

# While the form is visible, process events.
while ($form.Visible) {
  # Process form (UI) events.
  [Application]::DoEvents() 
  # Check if the connection needs refreshing
  if (([datetime]::UtcNow - $lastRefresh)).TotalMinutes -ge 10) {
    $null = Get-Mailbox -Identity someone@mywebsite.com
    $lastRefresh = [datetime]::UtcNow
  }
  # Sleep a little.
  Start-Sleep -Milliseconds 100 
}

Note that this does not try to determine if a connection refresh is actually required - it simply does it every 10 minutes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM