V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
xinghen57

powershell 管道问题

  •  
  •   xinghen57 · Apr 6, 2023 · 2159 views
    This topic created in 1128 days ago, the information mentioned may be changed or developed.

    看 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 replies    2023-04-06 22:48:26 +08:00
    geelaw
        1
    geelaw  
       Apr 6, 2023 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
       Apr 6, 2023
    @geelaw #1 太感谢了,醍醐灌顶。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3477 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:40 · PVG 18:40 · LAX 03:40 · JFK 06:40
    ♥ Do have faith in what you're doing.