Replace placeholders with actual values in PowerShell dictionary

后端 未结 1 740
春和景丽
春和景丽 2021-01-25 10:51

Following is the sample xml file:

 
  
    Dev
    Arizona

        
相关标签:
1条回答
  • 2021-01-25 11:29

    In general, when posting an example with xml or csv data, it is helpful to use here strings to represent the data instead of referencing a file that others do not have.

    Something like this can be used to achieve your result.

    $xmldata = @"
    <configuration>
        <environment id="Development">
        <type>Dev</type>
        <client>Arizona</client>
        <dataSource>Local</dataSource>
        <path>App_Data\%%type%%\%%client%%_%%dataSource%%</path>
        <targetmachines>
            <targetmachine>
            <name>Any</name>
            <remotedirectory>D:\Inetpub\Test</remotedirectory>
            </targetmachine>
        </targetmachines>
        </environment>
    </configuration>
    "@
    
    [System.Xml.XmlDocument] $configxml = [xml]$xmldata
    $environmentId = "Development"
    $keyValuePairs = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
    $configxml.SelectNodes("//configuration/environment[@id='$($environmentId)']//*[not(*)]") | `
        ForEach-Object {
                        if($_.ParentNode.ToString() -ne "targetmachine")
                        {
    
                            $keyValuePairs.Add($_.Name, $_.InnerText)
                        }
                    }
    
    "BEFORE---->"
    Write-Output $keyValuePairs
    
    # A static way...
    #$keyValuePairs.path = $keyValuePairs.path -replace '%%type%%', $keyValuePairs.type
    #$keyValuePairs.path = $keyValuePairs.path -replace '%%client%%', $keyValuePairs.client
    #$keyValuePairs.path = $keyValuePairs.path -replace '%%datasource%%', $keyValuePairs.datasource
    
    # Something more dynamic
    $m = [Regex]::Matches($keyValuePairs.path,"%%(.+?)%%*")
    $m | % {
        $tag = $_.Groups[1].Value
        $keyValuePairs.path = $keyValuePairs.path -replace "%%$tag%%", $($keyValuePairs.$tag)
    }
    
    "AFTER---->"
    Write-Output $keyValuePairs
    

    Note, if you wanted something totally dynamic in nature, it can be done by getting all the placeholders by some other method, like a regex with capture, but that seemed unnecessary based on the problem statement.

    0 讨论(0)
提交回复
热议问题