[使用RESTORE FILELISTONLY从数据库备份中获取逻辑文件名并将其存储到变量中

问题描述 投票:0回答:1

我正在使用一个相当简单的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)中包含的文件的逻辑文件名,并将它们存储在变量中,以便可以相应地重命名。

有人有什么想法吗?我已经为此撞了太久了! :)

感谢您的帮助!

sql-server powershell ps sqlps
1个回答
0
投票

与Powershell和SQL Server一样,Invoke-Sqlcmd是您的朋友。它返回一个易于浏览的数据表。 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"
© www.soinside.com 2019 - 2024. All rights reserved.