2015-02-24 89 views
1

當安裝了自定義控件的Nuget包時,我想在Web.config文件的<controls>部分內自動註冊控件。如何使用powershell腳本在Web.config文件中註冊自定義控件

我是Powershell腳本的新手。如果尚未添加以下行,請在Web.config文件的<controls>部分中添加以下行。

<add namespace="SimpleCustomControl" assembly="SimpleCustomControl" tagPrefix="custom" /> 

我已經添加了Install.ps1文件中的以下腳本:

# Install.ps1 
param($installPath, $toolsPath, $package, $project) 

$xml = New-Object xml 

# find the Web.config file 
$config = $project.ProjectItems | where {$_.Name -eq "Web.config"} 

# find its path on the file system 
$localPath = $config.Properties | where {$_.Name -eq "LocalPath"} 

# load Web.config as XML 
$xml.Load($localPath.Value) 

# Check whether the control is already registered 
$node = $xml.SelectSingleNode("configuration/system.web/pages/controls[@namespace='SimpleCustomControl']") 


# Not registered 
if ($node -eq $null) { 

# Register the custom control 
$contrlsNode = $xml.SelectSingleNode("configuration/system.web/pages/controls") 
# --> $contrlsNode.AddChild 

} 

# save the Web.config file 
$xml.Save($localPath.Value) 

任何人都可以請幫我在這裏?

卸載Nuget包時,是否可以從「Web.config」文件中刪除自定義控件<controls>部分?如果是這樣,在Uninstall.ps1文件裏面的PowerShell腳本是怎麼做的?

回答

1

看起來你已經想出了一切,但添加和刪除節點。

要追加新的XML節點,做這樣的事情:

$parentNode = $xml.SelectSingleNode("system.web/pages") 

$childNode = $xml.CreateElement("add") 
$childNode.SetAttribute("namespace", "SimpleCustomControl") 
$childNode.SetAttribute("assembly", "SimpleCustomControl") 
$childNode.SetAttribute("tagPrefix", "custom") 

$parentNode.AppendChild($childNode) 

這將創建一個新的節點,設置屬性,最後把它添加到父節點。

要刪除的節點上,使用相同的SelectSingleNode() XPath表達式找到它,你的樣品中使用,那麼

$node.ParentNode.RemoveChild($node) 

這是一個有點尷尬,但你不能刪除節點本身,您需要找到它的父母(.ParentNode)並刪除這個特定的孩子($node)。

+0

它像一個魅力工作!謝謝 :) – 2015-02-25 03:21:33

相關問題