Restore-SqlDatabase Wait operation timeout - database

I have setup a process for Restoring Databases using the Restore-SqlDatabase cmdlet and scheduled this into a SQl Agent job. It's been working fine until I tried to restore a 160GB database. It basically fails after 600s with the error "The wait operation timed out". I've tried adding in a StatementTimeout of 0 to see if it would get round this and also change the Remote query Timeout on the SQL Server but it still bobmbs out after 10 minutes. Does anyone know if there is another setting I can change to increase the timeout? The Code I'm running is:
# Load Module path! its not loading by default in calls from powershell
$env:PSModulePath=$env:PSModulePath + ";" + "C:\Program Files\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS\"
## Load module and run functions now
#Import SQL Server PowerShell Provider.
Import-Module "sqlps" -DisableNameChecking
#GEt Around Wait Timeout Error with Remote Connection via PoSh
$server = "THESERVER"
$serverConn = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
$serverConn.ConnectionContext.StatementTimeout = 0
#Restore Latest Copy of Test Database that was copied over
Restore-SqlDatabase -ServerInstance $server -Database "Test" -BackupFile "H:\SQLBACKUP\DATABASE_Refresh\Test_Latest.BAK" -ReplaceDatabase
Error That Appears is:
Restore-SqlDatabase : The wait operation timed out
At H:\SQLBACKUP\_AutoScripts\5_Test_DBRESTORE.ps1:16 char:1
+ Restore-SqlDatabase -ServerInstance $server -Database "Test ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Restore-SqlDatabase], Win32Exception
+ FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.RestoreSqlDatabaseCommand

It looks like Restore-SqlDatabase has a -ConnectionTimeout parameter:
Specifies the number of seconds to wait for a server connection before a timeout failure. The timeout value must be an integer between 0 and 65534. If 0 is specified, connection attempts do not timeout.
So your command can become:
Restore-SqlDatabase `
-ServerInstance $server `
-Database "Test" `
-BackupFile "H:\SQLBACKUP\DATABASE_Refresh\Test_Latest.BAK" `
-ReplaceDatabase `
-ConnectionTimeout 0

Related

Invoke-Sqlcmd error in Loop, No error once?

If I run this .ps1 script-
$secID = Invoke-Sqlcmd -ServerInstance "MyDBServer" -Database "MyDataBase"-Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host "MyDataBase"
Write-Host $secID.SysID
I get the following on the console with no error -
MyDataBase
18
However if I try this same query in a for loop in a larger script -
$dbservers = #('DataBaseServer1', 'DataBaseServer2')
foreach ($dbserver in $dbservers)
{
$databases = Get-SqlDatabase -ServerInstance $dbserver | Where-Object { $_.Name -Match '\d{3,4}' -and $_.Name -notlike '*test*'}
foreach ($database in $databases)
{
$secID = Invoke-Sqlcmd -ServerInstance $dbserver.Name -Database $database.Name -Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host $database.Name
Write-Host $secID.SysID
}
}
I get the correct query result but errors preceding it on the console -
Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that
the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
At \SQL.ps1:28 char:13
+ ... $secID = Invoke-Sqlcmd -ConnectionString $ConnectionString -Query ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At \SQL.ps1:28 char:13
+ ... $secID = Invoke-Sqlcmd -ConnectionString $ConnectionString -Query ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand*
MyDataBase
18
Why do I get errors when running it in the loop versus running it one time? Also why does the query work even though I get an error? I think I am missing something any help would be greatly appreciated!
I think its because you are calling property Name on a String, effectively returning nothing. try this (I just deleted the calling of the property $dbserver.Nameto $dbserver):
$dbservers = #('DataBaseServer1', 'DataBaseServer2')
foreach ($dbserver in $dbservers)
{
$databases = Get-SqlDatabase -ServerInstance $dbserver | Where-Object { $_.Name -Match '\d{3,4}' -and $_.Name -notlike '*test*'}
foreach ($database in $databases)
{
$secID = Invoke-Sqlcmd -ServerInstance $dbserver -Database $database.Name -Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host $database.Name
Write-Host $secID.SysID
}
}
The error must be because its looking for a DB instance "" and it doesn't find it, and the query might still go though because the the first server might not have an instance, or because those values were already loaded into the properties from before. But I'm just speculating, haven't really used this cmdlets.
PS: if you want to avoid calling empty properties add Set-StrictMode -Version 2 to your script, example:
PS > $text = "This is just a string"
PS > $text.AnyProperty
PS > Set-StrictMode -Version 2
PS > $text.AnyProperty
The property 'AnyProperty' cannot be found on this object. Verify that the property exists.
At line:1 char:1
+ $text.AnyProperty
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
Hope it helps.

Database Back Up using Powershell

I am trtying to take back up using poweshell
Below is the command which we are trying to execute,
Backup-SqlDatabase -ServerInstance "SERVER\DEFAULT" -Database "AFC" -BackupFile "\\REMOTESERVER\temp123\$dbName.bak"
However when we are trying to execute the same we are getting below error
Backup-SqlDatabase : Failed to connect to server 10.254.5.37\DEFAULT.
At line:1 char:1
+ Backup-SqlDatabase -ServerInstance "10.254.5.37\DEFAULT" -Database "A ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Backup-SqlDatabase], ConnectionFailureException
+ FullyQualifiedErrorId : Microsoft.SqlServer.Management.Common.ConnectionFailureException,Microsoft.SqlServer.Man
agement.PowerShell.BackupSqlDatabaseCommand
However when we are trying to execute Get-ChildItem command we are gettting names of all databases.
Please help us.
Regards,
Pradeep

Error thrown while taking backup of SQL Server content database using PowerShell

I am trying to take a backup of SQL Server content database using PowerShell.
Here is my code:
$dt = Get-Date -Format yyyyMMddHHmmss
$null =
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo");
$srvrvinstancename= "srvr-04\mssqlserver1"
$svr = New-Object
Microsoft.SqlServer.Management.Smo.Server($srvrvinstancename);
#Write-Output $svr WSS_Content_2d426b353ded49aa8ace920d4178c298
$bdir = "C:"
$svnm = $svr.Name
$db =
$svr.Databases['WSS_Content_2d426b353ded49aa8ace920d4178c298']
$dbname = $db.Name
$dt = get-date -format yyyyMMddHHmmss
$bfil = "$bdir\$($dbname)_db_$($dt).bak"
Backup-SqlDatabase -ServerInstance $svnm -Database $dbname -
BackupFile $bfil
but when I run the code I get the error:
Backup-SqlDatabase : The 'Backup-SqlDatabase' command was found in the module 'SQLPS', but the module could not be loaded. For more information, run 'Import-Module SQLPS'.
At line:19 char:1
+ Backup-SqlDatabase -ServerInstance $svnm -Database $dbname -BackupFile $bfil
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Backup-SqlDatabase:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModule
After that, I ran
import-module sqlps
But this also ran into error state:
Import-Module : File C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS\Sqlps.ps1 cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ Import-Module SQLPS
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [Import-Module], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand
What am I doing wrong?
I think you need to load a couple off Assembly:
# Load SQL server assemblies
#
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
# SmoExtended
#
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
UPDATE.
For scripts which can't be executed you need to do (as administrator in Powershell)
Set-ExecutionPolicy remotesigned

Restore database to new database and files using PowerShell

I have been trying unsuccessfully to restore a database to a new database but keep getting errors saying that the existing files cannot be overwritten. How do I specify a new database and files?
Update: The command I am using is below. TestDB_2.0 does not exist yet, I am wanting it to be created from the backup file.
Restore-SqlDatabase -ServerInstance SERVER-NAME\MSSQL2014 -Database TestDB_2.0 -BackupFile D:\TestWebsite\TestDeployments\testdb.bak -SqlCredential [sa, $pw]
The error I get is:
Restore-SqlDatabase : System.Data.SqlClient.SqlError: The file 'C:\Program Files\Microsoft SQL
Server\MSSQL12.MSSQL2014\MSSQL\DATA\TestDB.mdf' cannot be overwritten. It is being used by
database 'TestDB'.
At D:\Projects\Scripting\Scripts\Powershell\Backup-SqlDatabase.ps1:11 char:1
+ Restore-SqlDatabase -ServerInstance WIN-OJR1ILRNQUF\MSSQL2014 -Database TestDB_2 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Restore-SqlDatabase], SmoException
+ FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.RestoreSql
DatabaseCommand

Timeout issue in Backup-SQLDatabase cmdlet

I’m trying to take back-up of a large database using “Backup-SQLDatabase” cmdlet using following statement, but I’m getting time-out error after 10 minutes.
{Backup-SqlDatabase -ServerInstance $Server -Database $DatabaseName -BackupFile $BackUpFile -CompressionOption On -ConnectionTimeout 0 -Initialize -Verbose -ea Stop}
Here’s the error exactly after 600 seconds of execution :
VERBOSE: 60 percent processed.
VERBOSE: The backup or restore was aborted.
The wait operation timed out
+ CategoryInfo : InvalidOperation: (:) [Backup-SqlDatabase], Win3
2Exception
+ FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.P
owerShell.BackupSqlDatabaseCommand
+ PSComputerName : localhost
I looked up at internet and found a bug filled here.
However, the issue still exists in SQL Server 2012 (11.0.339).
I’ve also tried reconfiguring “remote query timeout” to 0 as given here, but the issue persists.
This is actually very weird issue. PowerShell is for automation and scripts do take more than 10 minutes to run. “Backup-SQLDatabase” should have considered this.
Please suggest a workaround by which I can fix this while using this cmdlet.
Else , I’ve to re-write the code using SMO classes or basic T-SQL.
I did some research on this and came around the following workaround :
$serverConn = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
$serverConn.ConnectionContext.StatementTimeout = 0
Backup-SqlDatabase -InputObject $serverConn -Database abc -BackupFile "L:\123\abc.bak"
When we pass Server name as a string, it tries to create it's own connection and we don't have the option to change QueryTimeout from 600 to 0.
However, we can create a SMO.Server object and use it after setting desired properties.
Hope it helps!

Resources