从字符串执行ScriptBlock时出错

时间:2016-04-21 06:55:42

标签: xml powershell-v3.0 powershell-v4.0

我有一个以下类型的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>

我的任务是让街道和郊区与地址类型相关 - 邮政的格式为街道,郊区。

我这样做的脚本如下所示 -

$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指出来。我现在已经修改了脚本以及运行脚本时遇到的新错误。

1 个答案:

答案 0 :(得分:0)

随着大量的挖掘和寻找替代方案,我能够管理一个变通方法。在这里 -

$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