When the code execution reaches the "finally" section, I get an error message that the session is already closed.
How can I check for that, so I don't try to stop the restore session if it is stopped already?
You have the same if statements in your try/finally sections. Moreover, your finally section will always be executed since $session variable wasn't redefined. Try the code below:
finally {
$exists = 'True'
while ($exists -eq 'True') {
$session = Get-VESQLRestoreSession | where {$_.Id -eq $session[0].Id}
if (!$session) {
Write-Host "Restore session with Id $($session[0].Id) has been stopped successfully."
$exists = 'False'
}
else {
Start-Sleep -Seconds 15
Write-Host "Awaiting for the session with Id $($session[0].Id) to stop."
}
}
}