You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PowerShell Select-Xml中调用XPath原生函数ends-with遇错求解

问题原因与解决方案

核心问题

PowerShell的Select-Xml基于.NET的XPath 1.0实现,而ends-with是XPath 2.0及以上版本才引入的函数,因此直接调用会触发错误——无论是否添加fn命名空间都无效,因为底层运行环境不支持XPath 2.0的函数集。

解决方案1:用XPath 1.0语法模拟ends-with效果

通过substring和string-length组合实现结尾匹配,这是XPath 1.0里的标准写法:

select-xml -path "/path/to/file.csproj" `
    -xpath "/Project/ItemGroup/ProjectReference[substring(@Include, string-length(@Include) - string-length('Something.csproj') + 1) = 'Something.csproj']"

逻辑说明:计算目标字符串的长度,从@Include属性的对应位置截取子串,再与目标值对比,达到匹配结尾的效果。

解决方案2:用PowerShell原生字符串过滤

先读取XML节点,再通过PowerShell的EndsWith()方法筛选,更直观易读:

# 读取XML文件
$xmlContent = [xml](Get-Content "/path/to/file.csproj")
# 获取所有ProjectReference节点并过滤
$xmlContent.SelectNodes("/Project/ItemGroup/ProjectReference") | 
    Where-Object { $_.Include.EndsWith('Something.csproj') }

补充说明

官方文档未提及XPath版本限制,是因为Select-Xml默认依赖.NET基础库的XPath 1.0实现,而XPath 2.0及以上的高级函数不在原生支持范围内。


内容的提问来源于stack exchange,提问作者Ian Kemp - SO dead by AI greed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:58:12