【问题标题】:Getting the Logical File Name using RESTORE FILELISTONLY from a DB backup and storing it into a variable使用 RESTORE FILELISTONLY 从数据库备份中获取逻辑文件名并将其存储到变量中
【发布时间】:2020-09-27 13:21:03
【问题描述】:

我正在使用一个相当简单的 PowerShell 脚本来自动化恢复数据库的过程:

    #Script to restore database.
    $serverInstance = $args[0]
    $dbName = $args[1]
    $file = $args[2]
    $dataDestination = $args[3]
    $logDestination = $args[4]

    Import-Module sqlps

    $relocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile(###LOGICALFILENAME###, $dataDestination)
    $relocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile(###LOGICALFILENAME###, $logDestination)

    Restore-SqlDatabase -ServerInstance $serverInstance -Database $dbName -BackupFile $file -RelocateFile @($relocateData,$relocateLog)

我正在寻找一种方法来动态获取数据库备份 ($file) 中包含的文件的逻辑文件名并将它们存储到变量中,以便可以相应地重命名。

有人有什么想法吗?我已经用头撞这个太久了! :)

感谢您的帮助!

【问题讨论】:

  • 尝试检查 Dbatools https://docs.dbatools.io/#Restore-DbaDatabase

标签: sql-server powershell ps sqlps


【解决方案1】:

与 Powershell 和 SQL Server 一样,Invoke-Sqlcmd 是您的朋友。它返回一个易于导航的 DataTable。 EG

$dt = Invoke-Sqlcmd "restore filelistonly from disk='c:\temp\aw.bak'"

$dataFileLogicalName = ""
$logFileLogicalName = ""
foreach ($r in $dt)
{
  if ($r.Type -eq "L")
  {
    $logFileLogicalName = $r.LogicalName
  }
  if ($r.Type -eq "D")
  {
    $dataFileLogicalName = $r.LogicalName
  }
  write-host "$($r.Type) $($r.LogicalName)  $($r.PhysicalName)"
}

write-host "data=$dataFileLogicalName  log=$logFileLogicalName"

【讨论】:

  • 谢谢一百万!终于在你的帮助下成功了!!!! :D
猜你喜欢
  • 1970-01-01
  • 2017-09-23
  • 2011-10-28
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多