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

PowerShell Get-Content与.Net Open路径解析差异及解决方案

问题根源

.NET 方法默认使用进程工作目录解析路径,该目录与PowerShell会话的当前工作目录不会自动同步。本次报错就是因为PowerShell当前工作目录为C:\src\t,但进程工作目录仍为PowerShell程序的启动目录C:\Program Files\PowerShell\7,导致.NET方法解析相对路径时定位到了错误的目录。

符合PowerShell原生规范的解决方案

优先使用PowerShell原生提供的$PSCmdlet.GetUnresolvedProviderPathFromPSPath()方法,将PowerShell风格的路径转换为.NET可识别的绝对路径,该方法天然支持相对路径解析、PowerShell内置驱动器转换、特殊路径字符处理,完全符合PowerShell的路径解析规则。

修改后的可运行代码

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [String]$Path
)
Write-Host "Path is $Path"
Get-Content -Path $Path | Out-Null
# 转换为.NET可识别的绝对路径
$absolutePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
if ([System.IO.StreamReader]$sr = [System.IO.File]::Open($absolutePath, [System.IO.FileMode]::Open)) { $sr.Close() }

说明:$PSCmdlet对象仅在添加了[CmdletBinding()]属性的脚本/函数中可用,现有代码已经满足该条件。

其他适配方案(适用特定场景)

  • 若目标路径确定已存在,可直接使用Convert-Path cmdlet获取绝对路径:
    $absolutePath = Convert-Path -Path $Path
    
  • 若需要先解析路径中的通配符,可使用Resolve-Path cmdlet:
    $absolutePath = Resolve-Path -Path $Path | Select-Object -ExpandProperty Path
    

内容的提问来源于stack exchange,提问作者lit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:45:02