将不同的内容保存到不同的文件[PowerShell]

dfddblmv  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(139)

我需要将不同的文本放在XML元素中,并将内容保存到不同的文件中,每个文本对应一个文件名。
我是菜鸟,我的代号是:

$texts = (
    "Text1",
    "Text2",
    "Text3",
    ...
)

$savePaths = (
    "c:\foo\myfile1",
    "c:\foo\myfile2",
    "c:\foo\myfile3",
    ...
)

function MyFunction {
    param (
        $Text,
        $SavePath
    )
    $xml = [XDocument]::new(
        [XElement]::new("Item",
            [XAttribute]::new("version", "1"),
            [XElement]::new("text", $Text)
            )
        )
    foreach ($SavePath in $savePaths) {
    $xml.ToString() | Out-File ("$($SavePath.ToLower()).xml")
    }
}

foreach ($text in $texts) {MyFunction -Text $text -SavePath $savePath}

它创建了所有的文件,但内容相同,如何修复?提前谢谢!

v1l68za4

v1l68za41#

如果这些数组$texts$savePaths对应,那么为什么不在此处使用模板-字符串来创建XML文件片段呢?

$texts     = "Text1","Text2","Text3"
$savePaths = "c:\foo\myfile1","c:\foo\myfile2","c:\foo\myfile3"

# for safety, get the smallest item count of both arrays

$items = [math]::Min($texts.Count, $savePaths.Count)

# create a template xml as Here-String

# placeholder {0} will be filled in inside the loop

$xmlTemplate = @'
<Item version="1">
  <text>{0}</text>
</Item>
'@

# and loop through the items in the arrays to write the files

for ($i = 0; $i -lt $items; $i++) {
    $xmlTemplate -f $texts[$i] | Set-Content -Path ('{0}.xml' -f $savePaths[$i].ToLower()) -Encoding UTF8
}

如果您将文本和文件路径组合在一个Hashtable对象中,效果会更好,如下所示:

$hash = @{
    "Text1" = "c:\foo\myfile1"
    "Text2" = "c:\foo\myfile2"
    "Text3" = "c:\foo\myfile3"
}

然后循环可以是这样的:


# create a template xml as Here-String

# placeholder {0} will be filled in inside the loop

$xmlTemplate = @'
<Item version="1">
    <text>{0}</text>
</Item>
'@

$hash.GetEnumerator() | ForEach-Object {
    $xmlTemplate -f $_.Key | Set-Content -Path ('{0}.xml' -f $_.Value.ToLower()) -Encoding UTF8
}

相关问题