File Directory Redirection with appended text

Microsoft Windows
Post Reply
jcoyle
Posts: 1
Joined: 2021-Dec-08, 2:38 pm

File Directory Redirection with appended text

Post by jcoyle »

I have a directory of SQL Backup files that I need to generate a file that I can use to restore these to the SQL database I can not just create a batch file and use the basic Dir /b pathToFiles > fileList.txt CMD. I need to append text before and after the file name. Please see example below

Directory Listing of Files
File-20211207-90121.bak
File-20211207-100456.trn
File-20211207-101457.trn
File-20211207-102457.trn

Redirected to a file with this format
RESTORE DATABASE [dbName] FROM DISK = 'C:\filePath\File-20211207-90121.bak' WITH NORECOVERY, REPLACE
RESTORE LOG [dbName] FROM DISK = 'C:\filePath\File-20211207-100456.trn' WITH NORECOVERY
RESTORE LOG [dbName] FROM DISK = 'C:\filePath\File-20211207-101457.trn' WITH NORECOVERY
RESTORE LOG [dbName] FROM DISK = 'C:\filePath\File-20211207-102457.trn' WITH NORECOVERY
RESTORE DATABASE [dbName] WITH RECOVERY

Although my example above is including the bak file, I would be happy with a solution that just produces a list just for the trn (Transactions files).

Any help would be greatly appreciated.

Joey
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: File Directory Redirection with appended text

Post by Simon Sheppard »

In PowerShell

Code: Select all

$files = dir c:\filepath\*.trn
$files | foreach-object {echo "RESTORE LOG [dbName] FROM DISK =' $_.name ' WITH NORECOVERY"}
In CMD

Code: Select all

FOR /f %%G in ('dir /b c:\filepath\*.trn') do echo RESTORE LOG [dbName] FROM DISK =' %%G ' WITH NORECOVERY
In both cases you can redirect the output to a file with >>somefile.txt
Post Reply