2017-02-01 213 views
0

我是PowerBSD的新手,但试图更多地采用以加快速度。Powershell:使用查找和替换替换文本文档中的唯一值

我有一个文本文件,指定SQL连接字符串(对这个问题不关键)。我正在查找的两个值是SQL Server名称和数据库名称。 SQL Server名称在每台机器上都会有所不同,因为它是本地实例,但数据库名称将保持不变。

从本质上讲,这里是字符串:

localSQLConString =数据库= Internal_TrainingProject;服务器= MBDatabase \ SQLEXPRESS14;集成安全性= TRUE;

我想过(使用用户提示)拉动到这些Powershell的作为变量,像这样:

param (
    [string]$SQL = $(Read-Host "Input SQL Server Instance Name.") 
    [string]$DB = $(Read-Host "Input SQL Database Name.") 
) 
(Get-Content "C:\Program Files (x86)\Test.txt") 

不过,我遇到了找你麻烦和替换件。每个文本文件都有共同点,比如localSQLConString =,Database =和Server =。

我希望做这样的事情

localSQLConString =数据库= $ DB;服务器= $ SQL;集成安全性= TRUE;

但我在分离变量之间的常见文本时遇到了问题。

任何你有任何帮助将不胜感激。

回答

0

尝试这样的事情

$connectionstring="Database=Internal_TrainingProject;Server=MBDatabase\SQLEXPRESS14;Integrated Security=True;" 

#split connectionstring to hash table 
[email protected]{} 
$connectionstring -split ";" | where {$_ -ne ""} | %{$Hash[$_.Split('=')[0]]=$_.Split('=')[1]} 

#modification elements 
$Hash['Server']=$SQL 
$Hash['Database']=$DB 

#create new connectionstring with elements modified 
$Newconnectionstring=($Hash.Keys | %{"$_=$($Hash[$_])"}) -join ";" 

$Newconnectionstring 
+0

感谢您的快速反应。这绝对有助于我获得我想要做的变量。我正在研究的下一件事是如何指定使用此信息实际获取和替换的文本。我可以调出Server =和Database =,但服务器或数据库名称中的字符数量会有所不同。有没有办法让它抓住=和;之间的字符串?例如,如果这是我替换的字符串localSQLConString = Database = Demodatabase; Server = DemoServer \ SQLEXPRESS14; Integrated Security = True; –