1

I am able to replace a single string in a SQL file using PowerShell as follows:

$newPrefix = "foo'
$dbUserMappingScriptPath = "C:\MySQL_Template.sql"
$updatedDbUserMapingScriptPath = "C:\MySQL.sql"
(gc $dbUserMappingScriptPath).Replace('DBPrefix_',$newPrefix) | sc $updatedDbUserMapingScriptPath

This is great for single scenarios, but I need to replace multiple strings. I have tried the following, but it doesn't perform the replace operation beyond replacing the first string of 'DBPrefix_' with $newPrefix. It does not perform the replacements for 'MDFDatabasePath' and 'LDFDatabasePath'.

How do I replace multiple strings given the following snippet? Note that this is wrapped in a Foreach-Object for the $.MDFDatabasePath and $.LDFDatabasePath values.

$dbUserMappingScriptPath = "C:\MySQL_Template.sql"
$updatedDbUserMapingScriptPath = "C:\MySQL.sql"
(gc $dbUserMappingScriptPath).Replace('DBPrefix_',$newPrefix).Replace('MDFDatabasePath',$_.MDFDatabasePath).Replace('LDFDatabasePath',$_.LDFDatabasePath) | sc $updatedDbUserMapingScriptPath

Here is a snippet of my SQL:

USE [master]
GO
CREATE DATABASE [DBPrefix_mydb] ON 
( FILENAME = N'MDFDatabasePath\DBPrefix_mydb.MDF' ),
( FILENAME = N'LDFDatabasePath\DBPrefix_mydb.ldf' )
 FOR ATTACH
GO

UPDATE: I had a mismatch in my PowerShell script in that I was running the replace on the wrong SQL script. The code above with an extra .Replace works like a charm

7
  • 2
    This should work. You should try to print the text after the first replace and ensure MDFDatabasePath is within your text. Also print out $_.MDFDatabasePath to ensure the variable is set. Commented Apr 6, 2016 at 18:21
  • MDFDatabasePath is in the text. Will check the variable setting soon
    – Kode
    Commented Apr 6, 2016 at 18:37
  • I tried hard coding a value and it failed to replace. Ex ('MDFDatabasePath','c:/SQL')
    – Kode
    Commented Apr 6, 2016 at 18:38
  • hm. can you post an reproducable example (content of $dbUserMappingScriptPath) Commented Apr 6, 2016 at 18:42
  • Updated with a snippet of the SQL.Of note is that the first replace of DBPrefix works
    – Kode
    Commented Apr 6, 2016 at 19:13

0

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.