Mizzle-Mo
Mizzle-Mo

Reputation: 598

Filter a file based on an object of string

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?

Upvotes: 1

Views: 128

Answers (1)

mjolinor
mjolinor

Reputation: 68243

$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.

Upvotes: 1

Related Questions