title: Restore database in remote SQL server using PowerShell
body: <p>I am working on restoring a database backup on a local server and restore in a remote SQL server. I see an error </p>
  
  <blockquote>
    <p>"Exception calling "SqlRestore" with "1" argument(s): "Restore failed
    for Server server\instance at  line:74 char:5"</p>
  </blockquote>
  
  <p>Not sure where is the issue. Please see code below.</p>
  
  <pre><code>[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
  [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
  [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum") | Out-Null
  
  if($useSqlServerAuthentication)
  {
  
      $passwordSecureString = ConvertTo-SecureString -String $pwd -AsPlainText -Force;
      $serverConnection = new-object Microsoft.SqlServer.Management.Common.ServerConnection $SR, $user, $passwordSecureString;
      $smoserver = new-object Microsoft.SqlServer.Management.Smo.Server $serverConnection;
  }
  else
  {
      $smoserver = new-object Microsoft.SqlServer.Management.Smo.Server $SR;
      write-host $smoserver
  }
  
  $dataFolder = $smoserver.Settings.DefaultFile;
  $logFolder = $smoserver.Settings.DefaultLog;
  
  if ($dataFolder.Length -eq 0)
  {
      $dataFolder = $smoserver.Information.MasterDBPath;
  }
  if ($logFolder.Length -eq 0) 
  {
      $logFolder = $smoserver.Information.MasterDBLogPath;
  }
  
  $backupDeviceItem = new-object Microsoft.SqlServer.Management.Smo.BackupDeviceItem $restorefile, 'File';
  $restore = new-object 'Microsoft.SqlServer.Management.Smo.Restore';
  $restore.Database = $Db;
  $restore.Devices.Add($backupDeviceItem);
  
  $dataFileNumber = 0;
  
  foreach ($file in $restore.ReadFileList($server)) 
  {
      $relocateFile = new-object 'Microsoft.SqlServer.Management.Smo.RelocateFile';
      $relocateFile.LogicalFileName = $file.LogicalName;
      if ($file.Type -eq 'D')
      {
          if($dataFileNumber -ge 1) { $suffix = "_$dataFileNumber"; }
          else { $suffix = $null; }
          $relocateFile.PhysicalFileName = "$dataFolder$DB.mdf";
          $dataFileNumber ++;
      }
      else 
      {
          $relocateFile.PhysicalFileName = "$logFolder\$DatabaseName$suffix.ldf";
      }
      $restore.RelocateFiles.Add($relocateFile) | out-null;
  }    
  $restore.SqlRestore($smoserver)
  </code></pre>