且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

阻止 Powershell XML 文件更新将输出发送到命令行?

更新时间:2023-11-27 15:04:16

SetAttributeNode 和 AppendChild 都输出信息所以我们只需要 $null[void] 那些出来

Both SetAttributeNode and AppendChild output information so we just need to $null or [void] those out

function Set-Webconfig-AppSettings
{
    param (
        # Physical path for the IIS Endpoint on the machine without the "web.config" part.
        # Example: 'D:\inetpub\wwwroot\cmweb510\'
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $path,

        # web.config key that you want to create or change
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $key,

        # Value of the key you want to create or change
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $value
    )

   Write-Host "Setting web.config appSettings for $path" -ForegroundColor DarkCyan

    $webconfig = Join-Path $path "web.config"
    [bool] $found = $false

    if (Test-Path $webconfig)
    {
        $xml = [xml](get-content $webconfig);
        $root = $xml.get_DocumentElement();

        foreach ($item in $root.appSettings.add)
        {
            if ($item.key -eq $key)
            {
                $item.value = $value;
                $found = $true;
            }
        }

        if (-not $found)
        {
        
            $newElement = $xml.CreateElement("add");
            $nameAtt1 = $xml.CreateAttribute("key")
            $nameAtt1.psbase.value = $key;
            $null = $newElement.SetAttributeNode($nameAtt1);

            $nameAtt2 = $xml.CreateAttribute("value");
            $nameAtt2.psbase.value = $value;
            $null = $newElement.SetAttributeNode($nameAtt2);

            $null = $xml.configuration["appSettings"].AppendChild($newElement);
        }
    
        $xml.Save($webconfig)
    }
    else
    {
        Write-Error -Message "Error: File not found '$webconfig'"
    }
}