I found a solution to make sure that the restauration completed successfuly by using the stored procedure sp_help_jobhistory , here's the link for documentation: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-help-jobhistory-transact-sql?view=sql-server-ver15.
Here's the script:
[string]$output;
$Query =@"
USE msdb;
GO
declare @temp table
(
job_id varchar(255),
job_name varchar(255),
run_status varchar(255),
run_date varchar(255),
run_time varchar(255),
run_duration varchar(255),
operator_emailed varchar(255),
operator_netsent varchar(255),
operator_paged varchar(255),
retries_attempted varchar(255),
server varchar(255)
);
INSERT @temp Exec dbo.sp_help_jobhistory @job_name = N'JobName';
select top 1 run_status from @temp order by run_date Desc, run_time ;
GO
"@
$output = Invoke-Sqlcmd -ServerInstance xxxxxx -Database xxxxx -Username xxx -Password xxxx -Query $Query
$result = $output.itemArray
if ($result -eq '1'){
Write-Host "Restauration succeded"
}
else { Write-Host "Restauration failed"}
I used a temporary table to read the content of the stored procedure, then I got the last job executed by ordering the result of the select query.
Also I added this script in a step before to test the restauration completion, because I can't access the database while it is in the restoration phase.
[string]$sucess = 'false'
$i = 0;
$ErrorActionPreference= 'silentlycontinue'
$query =@"
SELECT * FROM tiers Where id = 1;
GO
"@
do{
Invoke-Sqlcmd -ServerInstance xxxxxx -Database xxxxx -Username xxx -Password xxxx -Query $query
if($?){
$sucess = 'true';
break;
}
Write-Host "Echec"
start-sleep -Seconds 60
$i++
} While ($i -le 2 )
if ($sucess -eq 'true'){
Write-Host "Success"
}
Else {
Write-Host "Wait for too long, you need to manually check the restauration steps"
}
You can simply add the do...While in the first script, in my case I need to test the completion of restauration seperately from the script that checks the status of it.