powershell 在ForEach-Object中正确处理哈希表值

zdwk9cvp  于 2023-01-05  发布在  Shell
关注(0)|答案(1)|浏览(218)

我有一个.xml文件,我想用它来创建Windows .url文件:

<?xml version="1.0" encoding="UTF-16" ?>
<items_list>
<item>
<title>About topics - PowerShell | Microsoft Learn</title>
<url>https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about?view=powershell-7.3</url>
</item>
<item>
<title>PowerShell HashTable - Everything you need to know — LazyAdmin</title>
<url>https://lazyadmin.nl/powershell/powershell-hashtable/</url>
</item>
<item>
<title>How a Regex Engine Works Internally</title>
<url>https://www.regular-expressions.info/engine.html</url>
</item>
</items_list>

我把标题和网址放到一个Hashtable中:

$InXML = [XML](Get-Content .\test.xml)
$BookMarks = [ordered]@{
Title = (Select-Xml -xml $InXML -XPath "//title" | % {$_.Node.InnerXml}) -replace '\?|\\|/|:'
URL   = Select-Xml -xml $InXML -XPath "//url" | % {$_.Node.InnerXml}
}

到目前为止一切都很好,但当我尝试循环TitlesURLs时,我开始遇到问题:

$wshshell = New-Object -ComObject WScript.Shell
$BookMarks | ForEach-Object {
    $Title = $_.Title
    $Url = $_.Url
    Write-Output $shortcutFilePath
    # $shortcutFilePath = Join-Path -path "c:\temp" -ChildPath "$Title.Url"
    # $shortcut = $shell.CreateShortcut($shortcutFilePath)
    # $shortcut.TargetPath = "$Url"
    # $shortcut.Save()
    
}

我注解掉了循环中的actuall代码,以查看Write-Output实际上发生了什么。所有的键值都连接成一个长标题或一个长.url
我所期望的是一次只获得一对URL和Title,这样我就可以在循环中创建.url文件。
阅读有关如何做到这一点的文档和文章。我尝试了以下几种变化:

$BookMarks.Values | ForEach-Object {
    $Title = $_.Title
    $Url = $_.Url
  Write-Output $Title
  Write-Output $Url
  }

我不断得到空变量。任何帮助或想法将是非常感谢。

inn6fuwd

inn6fuwd1#

我建议简化和精简您的代码,如下所示,这将绕过您的问题:

[xml] $inXML = Get-Content -Raw .\test.xml

$inXml.items_list.item | ForEach-Object {
  $title = $_.Title
  $url = $_.Url
  "[$title] [$url]" # sample output.
  # ... work with $title and $url here
  # $wshshell = New-Object -ComObject WScript.Shell
  # ...
}

上面使用了PowerShell's adaptation of the XML DOM,它允许您访问元素和属性,就好像它们是 properties 一样。

相关问题