I have this regex that works fine on C#:
\s*use\s+(.*?)([\r]{0,1}\n)
I have tried using it (or similar versions of it) on Powershell but it doesn't work. Can someone help me ?
Some failed attempts:
$query = [regex]::Replace($query, "\s*use\s+(.*?)([`r]{0,1}`n)", ("USE [" + $database + "]"), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Multiline)
$query = [regex]::Replace($query, "\s*use\s+([^`r]{1,}?)([`r])", ("USE [" + $database + "]$2"), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Multiline)
$query = $query -ireplace "\s*use\s+(.+)([\r]{0,1})", ("USE [" + $database + "]"
Some questions:
Do I need to use
`r`nto get C#'s\r\n??? (I am not yet familiar with PowerShell...)Since my 1st attempt seems to be using a .NET function, shouldn't this function work as it works on .NET? (because I think I see some differences but I can't pinpoint the cause - is it because of the escape characters?)
How is my first regex (presented above) translated into Powershell (either with [regex]::Replace() or with -ireplace)?
UPDATE
Data to test against (I use it to change the default DB in SQL scripts):
CREATE LOGIN [test] WITH PASSWORD=N'j-9sfjhpsojhp',
DEFAULT_DATABASE=[test], DEFAULT_LANGUAGE=[us_english],
CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
USE test
GO
/****** Object: User [test] Script Date: 10/07/2011 16:39:48 ******/
GO
CREATE USER [test] FOR LOGIN [test] WITH DEFAULT_SCHEMA=[dbo]
GO
Using a C# tool I get the USE line correctly (and I can replace it using sth like this : $2USE NewDb$2).
When using this (that uses the same regex) in Powershell, it doesn't work (I still get the USE test printed):
$database = "NewDb"
$query = Get-Content '<path to sql file>'
$query = [regex]::Replace($query, '\s*use\s+(.*?)([`r]{0,1}`n)', ("USE [" + $database + "]"), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Multiline)
$query
UPDATE
A working solution:
$database = "NewDb"
$query = (Get-Content '<file path>') -join "`r`n"
$query = [regex]::Replace($query, '^\s*use\s+(.*?)$', ("`nUSE [" + $database + "]`n"), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Multiline)
$query
However, newlines still don't work as in the .NET version.