1

I have a SQL restore script (file on file system) that contains a list of databases to be restored like so:

RESTORE DATABASE DB1... RESTORE DATABASE DB2... RESTORE DATABASE DB3...

I then have an object that contains a list of databases that are already online.

$onlineDatabases.Database outputs DB1 DB2

How can I return a new restore script that contains only the DB3 database?

1 Answer 1

1
$online_databases = new-object psobject -property @{database = @("DB1","DB2")}
$test_script = "RESTORE DATABASE DB1","RESTORE DATABASE DB2","RESTORE DATABASE DB3"

[regex]$online_regex = "RESTORE DATABASE " + '(‘ + (($online_databases.database |foreach {[regex]::escape($_)}) –join “|”) + ‘)’
$new_script = $test_script -notmatch $online_regex

$new_script

RESTORE DATABASE DB3

Replace the $test_script with get-content on your script file, and pipe $new_script to out-file to save it.

Sign up to request clarification or add additional context in comments.

4 Comments

When I run this in my script, $new_script returns True instead of the script.
Scratch that it was a PowerShell ISE fail. It is returning nothing. I will see if I can figure it out.
Here's an explanation of that regex if it helps: blogs.technet.com/b/heyscriptingguy/archive/2011/02/18/…
Thanks man, I had to tweak it a bit because there was something wrong with my object. I think because Database was listed as a NoteProperty? I had to use $onlineDatabases and then convert your Regex to a string and then find and replace on {Database= to "" and on } and on \@ after I did that it worked!!!! Thanks man, I don't know why my search skills didn't turn up the link, but you helped me get unblocked on my project. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.