首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串执行ScriptBlock时出错

从字符串执行ScriptBlock时出错
EN

Stack Overflow用户
提问于 2016-04-21 06:55:42
回答 1查看 474关注 0票数 0

我有一个以下类型的xml -

代码语言:javascript
复制
<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 -邮政在格式街,郊区.

我的剧本如下所示-

代码语言:javascript
复制
$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 

运行上面的块会给我一个奇怪的错误。如下图所示-

代码语言:javascript
复制
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;那么,我将使用字符串操作实现的$LeafNodes将如下面所示

代码语言:javascript
复制
 $LeafNodes= "$($_.Street) ; $($_.Suburb)" 

有人能帮我解决这个转换类型的失败吗?我不能选择将整个东西存储在另一个.ps1中。我的实际任务是从许多复杂的xml中查找和连接数据节点。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-22 05:37:41

嗯,随着大量的挖掘和寻找替代方案,我能够找到一个解决办法。它开始了-

代码语言:javascript
复制
$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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36761872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档