【问题标题】:Error executing ScriptBlock from string从字符串执行 ScriptBlock 时出错
【发布时间】:2016-04-21 06:55:42
【问题描述】:

我有以下类型的 xml -

<Test>
<Address>
    <AddressType>Postal</AddressType>
    <Street>123</Street>
    <Suburb>Rhodes</Suburb>
</Address>
<Address>
    <AddressType>Commmunication</AddressType>
    <Street>345</Street>
    <Suburb>Liberty Grove</Suburb>
</Address>

我的任务是获取与 AddressType - Postal 格式相关的 Street 和 Suburb,格式为 Street, Suburb。

我的脚本如下所示 -

$Path = "C:\Testing.xml"
$XPath = "/Test/Address[AddressType='Postal']"
$LeafNodes ="$($_.Street) , $($_.Suburb)"

$xml = New-Object xml
$xml.Load($Path)

$string = @"
select-xml -Xml "$($xml)" -XPath "$($XPath)" | 
        select -ExpandProperty Node |
        select @{N="FullAddress";E={"$LeafNodes"}} | 
        select -ExpandProperty FullAddress 
"@


$ScriptBlock = [scriptblock]::Create($string)
.$ScriptBlock 

运行上面的代码块给了我一个奇怪的错误。如下图-

Select-Xml : Cannot bind parameter 'Xml'. Cannot convert the "System.Xml.XmlDocument" value of type 
"System.String" to type "System.Xml.XmlNode".
At line:1 char:17
+ select-xml -Xml "System.Xml.XmlDocument" -XPath "/Test/Address[AddressType='Post ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Xml], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.SelectXmlCom 
   mand

我的实际任务是 LeafNode 变量将来自另一个映射文件。

假设该文件需要数据是 Street;Suburb 然后是 $LeafNodes ,我将使用一些字符串操作来实现,如下所示

 $LeafNodes= "$($_.Street) ; $($_.Suburb)" 

有人可以帮助我解决这种转换类型失败的问题吗?我无法寻找将整个内容存储在另一个 .ps1 中的选项。我的实际任务涉及从大量复杂的 xml 中查找和连接数据节点。

编辑- 感谢 har07 指出。我现在已经修改了脚本和运行脚本时遇到的新错误。

【问题讨论】:

  • 正如错误消息提示的那样,您使用 xpath 而不是路径来加载 xml:$xml.Load($XPath)

标签: xml powershell-3.0 powershell-4.0


【解决方案1】:

通过大量的挖掘和寻找替代方案,我能够管理一个解决方法。就这样 -

$Path = "C:\Testing.xml"
$DesiredOutput = "*Street*,*Suburb"
$XPath = "/Test/Address[AddressType='Postal']" 

# variable to ensure only non special characters
# are identified
$Pattern = "^[a-zA-Z0-9\s]+$"

$xml = New-Object -TypeName System.Xml.XmlDocument


$xml.Load($Path)
#get the target node whose child elements are 
# needed to be manipulated
$targetNode = Select-Xml -Xml $xml -XPath $XPath

# Split the desired output into an array
# here * is the seprator to get the Nodes
$Nodes = $DesiredOutput -split '\*'

# variable to store the output 
$output = $null

# loop through each node and get the corresponding
# values and store it in the output variable

foreach($Node in $Nodes)
{
    if($Node -match $Pattern ){

        $output += [string]($targetNode.Node.SelectSingleNode($Node).'#text') 
    }
    else{
        $output += $Node 
    }
}
#get the output 
$output 

【讨论】:

    猜你喜欢
    • 2013-06-05
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多