2012-04-26 24 views
3

如何在web.config中向system.serviceModel添加節,如果它尚不存在?如何使用PowerShell將節添加到web.config中?

前:

<system.serviceModel> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 
</system.serviceModel> 

後:

<system.serviceModel> 
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 
<bindings> 
     <basicHttpBinding> 
     <binding name="ValidationServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
      <security mode="Transport"> 
      <transport clientCredentialType="Ntlm" /> 
      <message clientCredentialType="UserName" /> 
      </security> 
     </binding> 
     </basicHttpBinding> 
<bindings> 
</system.serviceModel> 
+0

爲什麼你想從PowerShell做到這一點?它似乎並不適合這項工作。 – 2012-04-26 23:19:51

+0

因爲它是自動化部署服務,而且手足夠。 – 2012-04-26 23:23:05

回答

5

這不是太糟糕了這樣做在PowerShell中:

$origXml = [xml]@' 
<configuration> 
<system.serviceModel> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 
</system.serviceModel> 
</configuration> 
'@ 

$newXml = @' 
<bindings> 
     <basicHttpBinding> 
     <binding name="ValidationServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
      <security mode="Transport"> 
      <transport clientCredentialType="Ntlm" /> 
      <message clientCredentialType="UserName" /> 
      </security> 
     </binding> 
     </basicHttpBinding> 
</bindings> 
'@ 

if (!$origXml.configuration.'system.serviceModel'.bindings) 
{ 
    $tempXmlDoc = new-object System.Xml.XmlDocument 
    $tempXmlDoc.LoadXml($newXml) 
    $newNode = $origXml.ImportNode($tempXmlDoc.DocumentElement, $true) 
    $origXml.configuration.'system.serviceModel'.AppendChild($newNode) 
} 

注意,這種方法只適用,因爲XML你想注入具有單根元素<bindings>

+0

如何從打開的XML文件中使用它? $ xml = [xml](Get-Content $ MainBinding)#$ MainBinding - web.config文件中的變量 - C:\ web.config $ xml.Save($ MainBinding) – 2012-04-27 00:30:24

+0

在上面的例子中,'$ origXml' *是*一個開放的XML文件。 '$ newXml'只是一個有效的XML字符串片段。 – 2012-04-27 00:38:37

+0

反應它的工作! – 2012-04-27 00:49:44

相關問題