Restore database to new database and files using PowerShell - sql-server

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

Related

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

Get-SqlInstance connection failure

Test-Connection reaches the server successfully. What might be the root cause of:
>Get-SqlInstance -ServerInstance 'DEVSQL02'
Get-SqlInstance : Failed to connect to server DEVSQL02.
At line:1 char:1
+ Get-SqlInstance -ServerInstance 'DEVSQL02'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DEVSQL02:String) [Get-SqlInstance], ConnectionFailureException
+ FullyQualifiedErrorId : ConnectionToServerFailed,Microsoft.SqlServer.Management.PowerShell.GetSqlInstanceCommand
From help Get-SqlInstance.
SYNTAX
Get-SqlInstance [[-Credential] <PSCredential>] [-ConnectionTimeout <Int32>] [-Script] [-ServerInstance <String[]>] [-Confirm] [-WhatIf] [<CommonParameters>]
Must PowerShell Remoting be enabled? Is port 1433 involved?
Using PowerShell 5.1.14409.1018 on Windows 7 Professional.
SqlServer module 21.1.18068.

Restore-SqlDatabase Wait operation timeout

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

SQL Server PowerShell error Get-ChildItem

I try to get backup from SQL databases with this PowerShell code:
Set-Location "SQLSERVER:\SQL\computer\distance\Databases"
foreach ($database in (Get-ChildItem)) {
$dbName = $database.Name
Backup-SqlDatabase -Database $dbName -BackupFile "E:\bu\$dbName"
}
In a virtual server it works.
When I go to SQLSERVER:\SQL\computer\distance\Databases location and take ls
it show my databases and sucessfully takes backups.
But in another server in my workplace it gives this error:
Get-ChildItem : SQL Server PowerShell provider error: Failed to read child items.
[Failed to connect to server computer\instance. --> Login failed for user
'work\sql'.]
At line:1 char:23
+ ForEach($database in (Get-ChildItem))
+ ~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (SQLSERVER:\SQL\...\instance\Databases:SqlPath) [Get-ChildItem], GenericProviderException
+ FullyQualifiedErrorId : CannotReadChildItems,Microsoft.PowerShell.Commands.GetChildItemCommand
and when in SQLSERVER:\SQL\computer\distance\Databases directory I do ls it gives this error:
ls : SQL Server PowerShell provider error: Failed to read child items. [Failed to
connect to server computer\instance. --> Login failed for user 'work\sql'.]
At line:1 char:1
+ ls
+ ~~
+ CategoryInfo : ReadError: (SQLSERVER:\SQL\...\instance\Databases:SqlPath) [Get-ChildItem], GenericProviderException
+ FullyQualifiedErrorId : CannotReadChildItems,Microsoft.PowerShell.Commands.GetChildItemCommand
computer\instance: I changed for this example.

Trying to get the status of mirrored databases using powershell

I am trying to test the following script in powershell which gets the status of the mirrored databases.
#SQL Variables
$sqlservers = "APNSQL01"
#SQL database mirroring status
$body +=echo "------------Originating Server-----------"`r`n""`r`n""
Import-Module "sqlps" -DisableNameChecking
$body +=echo "--------Status of mirrored databases---------"`r`n""`r`n""
foreach ($server in $sqlservers){
$body +=echo "Database mirroring state on $server
"
$body += Invoke-Sqlcmd -Query "USE master
SELECT sys.database_mirroring.mirroring_state_desc
,sys.databases.name
FROM sys.database_mirroring INNER JOIN sys.databases ON sys.database_mirroring.database_id=sys.databases.database_id
WHERE mirroring_state_desc IS NOT NULL" -ServerInstance "$server" | out-string
}
When I run this code, I get the following error :
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 C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
My SQL server is a STANDARD database. It has no mirror. Is that the issue?
What might the error be?

Resources