PowerShell脚本本地正常但Appveyor CI报错:找不到接受参数'fix'的位置参数
问题描述
本地PowerShell 7.3.9环境中,以下脚本可正常将指定目录下的XML文件路径数组赋值给$specs,但在Appveyor CI的PowerShell 7.3.8环境执行时报错:
Join-Path : A positional parameter cannot be found that accepts argument 'fix'. At C:\projects\myproj-jib50\scripts\Generate-Message-Sources.ps1:8 char:10 + $specs = Join-Path $rootpath spec fix *xml | Resolve-Path + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Join-Path], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.JoinPathCommand No input files.
涉及的脚本代码:
$rootpath = Join-Path $PSScriptRoot '..' | Resolve-Path $specs = Join-Path "$rootpath" spec fix *xml | Resolve-Path
请问是否是PowerShell版本差异导致的该问题?
问题原因与解决方法
确实是PowerShell版本差异引发的问题。
PowerShell 7.3.9对Join-Path cmdlet做了功能更新,允许直接传入多段路径作为位置参数(例如Join-Path root a b c这种写法),但7.3.8及更早版本的Join-Path不支持该特性——它仅接受两个位置参数:路径前缀和子路径,多余的参数会被判定为无效位置参数,进而抛出你遇到的错误。
要让脚本兼容两个版本,你需要调整Join-Path的调用方式,以下几种写法都能满足需求:
方法1:嵌套调用Join-Path
$specs = Join-Path (Join-Path (Join-Path "$rootpath" spec) fix) *.xml | Resolve-Path
方法2:通过-ChildPath参数传递完整子路径
$specs = Join-Path "$rootpath" -ChildPath "spec/fix/*.xml" | Resolve-Path
方法3:直接使用Get-ChildItem定位文件
$specs = Get-ChildItem -Path "$rootpath\spec\fix\*.xml" | Resolve-Path
以上写法在PowerShell 7.3.8和7.3.9环境中均可正常运行。
内容的提问来源于stack exchange,提问作者Grant Birchmeier
相关产品推荐
相关产品推荐

