2009-05-16 14 views

Odpowiedz

28

Biorąc pod uwagę to próbka App.config: C: \ Sample \ app.config:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
     <add name="dbConnectionString" 
      connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/> 
    </connectionStrings> 
</configuration> 

Poniższy skrypt C: \ Sample \ Script.ps1 będzie odczytywać i zapisywać ustawienia:

# get the directory of this script file 
$currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path) 
# get the full path and file name of the App.config file in the same directory as this script 
$appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config') 
# initialize the xml object 
$appConfig = New-Object XML 
# load the config file as an xml object 
$appConfig.Load($appConfigFile) 
# iterate over the settings 
foreach($connectionString in $appConfig.configuration.connectionStrings.add) 
{ 
    # write the name to the console 
    'name: ' + $connectionString.name 
    # write the connection string to the console 
    'connectionString: ' + $connectionString.connectionString 
    # change the connection string 
    $connectionString.connectionString = 'Data Source=(local);Initial Catalog=MyDB;Integrated Security=True' 
} 
# save the updated config file 
$appConfig.Save($appConfigFile) 

Wykonaj skrypt:

PS C:\Sample> .\Script.ps1 

wyjściowa:

name: dbConnectionString 
connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True 

Updated C: \ Sample \ App.config:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <connectionStrings> 
    <add name="dbConnectionString" 
     connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" /> 
    </connectionStrings> 
</configuration> 
+0

Bardzo przydatna odpowiedź dziękuję @ Robin – 101V

20

Kod może być znacznie więcej krótszy (na podstawie app.config Robin):

$appConfig = [xml](cat D:\temp\App.config) 
$appConfig.configuration.connectionStrings.add | foreach { 
    $_.connectionString = "your connection string" 
} 

$appConfig.Save("D:\temp\App.config") 
+1

Fajnie, dziękuję za cynk. Nie zdawałem sobie sprawy, że mogę użyć tej składni. – Robin

+2

Jeśli dążymy do skrócenia, foreach należy zapisać jako%. –

Powiązane problemy