V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xinghen57
V2EX  ›  PowerShell

powershell 管道问题

  •  
  •   xinghen57 · 2023-04-06 22:14:00 +08:00 · 1134 次点击
    这是一个创建于 379 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看 Powershell Rename-Item 文档时,有批量命名文件的 example ,代码如下:

    Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.log' }
    

    无法理解 Get-ChildItem 获取的文件后,通过管道,具体是使用哪种方式传递给 Rename-Item ,以及传递了什么内容。

    上面代码我的理解,Get-ChildItem 命令的结果通过管道传递给了 Rename-Item 的 Path 参数。但 Path 只接受 string 。如果管道是 ByValue 方式,传递的应该是 Object ,所以不是 ByValue 。如果是 ByPropertyName ,Get-ChildItem 获取的 FileInfo 对象并没有 Path 属性,理论上也无法传递。

    2 条回复    2023-04-06 22:48:26 +08:00
    geelaw
        1
    geelaw  
       2023-04-06 22:31:03 +08:00 via iPhone   ❤️ 1
    看文档就知道了,LiteralPath 可以 ByPropertyName 而且有别名 PSPath ,而 PowerShell 的 provider 返回的对象都用 PowerShell 扩展系统增加了 PSPath 属性。

    传入 Path 是错误的,,当然不能认为传入了 Path ,因为中括号既是合法文件名也是 PowerShell Path 字符串的通配符,这会导致带有中括号的文件名解读错误。此外 Path 的性能也不如 LiteralPath 。

    除了看文档,搜索也可以解决这个问题 https://stackoverflow.com/questions/57456944/nonexistent-literalpath-property-of-system-io-fileinfo-object-bound-to-parameter
    xinghen57
        2
    xinghen57  
    OP
       2023-04-06 22:48:26 +08:00
    @geelaw #1 太感谢了,醍醐灌顶。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2755 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:04 · PVG 08:04 · LAX 17:04 · JFK 20:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.