在Powershell中获取自定义的web.config部分及其内容

我有一个Web应用程序安装在c:\inetpub\wwwroot_Site1\AppName ,它具有自定义部分组和部分,如下所示:

 <configSections> <sectionGroup name="Libraries"> <section name="Custom.Section.Name" type="System.Configuration.NameValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/> <section name="Custom.Section.Name2" type="System.Configuration.NameValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/> </sectionGroup> </configSections> 

我已经写了Powershell的以下片段:

 Import-Module WebAdministration Get-WebConfiguration //Libraries IIS:\Sites\Site1\AppName 

哪个正确返回:

命名部分组

==== ======== ===========

库Custom.Section.Name

Custom.Section.Name2

我无法理解的是,无论是通过Get-WebConfiguration还是Get-WebConfigurationProperty可以访问实际“body”中的CustomSectionName的直接子元素的<add key="x" value="y" />的configuration文件。

恰巧我最近把这个函数放到我编写的PowerShell Web框架中。

以下是您需要的三行代码:

 Add-Type -AssemblyName System.Web $webConfigStore = [Web.Configuration.WebConfigurationManager]::OpenWebConfiguration($path) $customSetting = $webConfigStore.AppSettings.Settings["$Setting"]; 

第三个会有所不同,取决于你想要得到什么。

希望这可以帮助

如果该Web应用程序是SharePoint 2007品种,则可以通过以下方式从其web.config中选取一个appSetting:

 param ( [string] $url='http://contso.com') [System.Reflection.Assembly]::LoadWithPartialName('System.Web') | Out-Null [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint') | Out-Null [Microsoft.SharePoint.SPSite] $site = New-Object -TypeName 'Microsoft.SharePoint.SPSite' -ArgumentList $url [System.Configuration.Configuration] $config = [System.Web.Configuration.WebConfigurationManager]::OpenWebConfiguration('/', $site.WebApplication.Name) <p># pull the one appSetting string we're interested in [string] $appSettingKey = 'avalidkey' [string] $appSettingValue = $config.AppSettings.Settings[$appSettingKey].Value Write-Host ("<appSetting> Key={0}, Value={1}" -f $appSettingKey, $appSettingValue) $config = $null $site.Dispose() $site = $null