Powershell:使用“查找和替换”替换文本文档中的唯一值

时间:2017-02-01 16:15:24

标签: powershell

我对powershell非常陌生,但试图接受更多的东西加速。

我有一个指定SQL连接字符串的文本文档(对这个问题并不重要)。我正在寻找的两个值是SQL Server Name和数据库名称。每台计算机上的SQL Server名称都不同,因为它是本地实例,但数据库名称将保持不变。

基本上,这是字符串:

localSQLConString = Database = Internal_TrainingProject; Server = MBDatabase \ SQLEXPRESS14; Integrated Security = 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 = Database = $ DB ; Server = $ SQL ; Integrated Security = True;

但我在拆分变量之间的公共文本时遇到了麻烦。

非常感谢任何人的帮助。

1 个答案:

答案 0 :(得分:0)

尝试类似这样的事情

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

#split connectionstring to hash table
$Hash=@{}
$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
相关问题