hamin.se
  • About
  • All posts

SQL backup logicalname as a variable in powershell - Mon, Jan 25, 2016

Not sure why you’d like to do this, but I’ve used it for a backup script.

    # Connect SQL server using SMO Server object, then create a Restore object
    $srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') SQL-SERVER-NAME
    $rs = new-object('Microsoft.SqlServer.Management.Smo.Restore')

    # Define a backup device item pointing to the backup file, add that to the devices collection of the restore object
    $bckfile = "C:\MSSQL\LOCATION-TO-BACKUP.bak"
    $bdi = new-object ('Microsoft.SqlServer.Management.Smo.BackupDeviceItem') ($bckfile, 'File')
    $rs.Devices.Add($bdi)

    # Use readfilelist() method of the restore object to get the details from the backup file
    $fl = $rs.ReadFileList($srv)

    # Add the logical file names from the read file list in an array
    $logname = @($fl).logicalname

    # The first object of the array is the logical name of the backup
    $logname= $logname[0]

    # Print the logical name on screen
    write-host $logname

Back to Home


© 2024 | Built on Hugo

Twitter Linkedin GitHub