I have a function to restore sql server database using “Microsoft.SqlServer.Management.Smo.Restore. There is an event called completed and within the code I put
Register-ObjectEvent -InputObject $restore -EventName "Complete" -SourceIdentifier CompleteRestore -Action { Write-Host "Works"} | Out-Null
It works perfectly and the message appears when the restore finishes.
When I run the function by Powershell Job, The restore is done,but the message does not appear.
Can You Help me guys ?
Thanks
I am using this code to run the function as a job and the Register-Object is inside the Invoke-SqlRestoreEventing Function
$server = "."
$dbname = "TestPoshEventing_6"
$filepath = "c:\temp\backup\TestPoshEventing.bak"
$Realocatefiles = @{TestPoshEventing='c:\temp\restore\TestPoshEventing_6.mdf';TestPoshEventing_log='c:\temp\restore\TestPoshEventing_6.ldf'}
Start-Job -Name "Restore1" -InitializationScript {Import-Module c:\temp\testes\PoshTest.psm1 -Force} -scriptblock { Invoke-SqlRestoreEventing -sqlserver $args[0] -dbname $args[1] -filepath $args[2] -relocatefiles $args[3] -force } -ArgumentList $server, $Dbname ,$filepath ,$Realocatefiles
Background jobs run in a different runspace. So, anything you output there won’t appear at the console. You can modify your code to do that. Check this for example,
By using
Receieve-Jobwhen the background job completes, you can see the output of yourregister-ObjectEvent.