【问题标题】:PowerShell Rename-Item on Long Named Files Warning RemovalPowerShell Rename-Item on Long Named Files 警告删除
【发布时间】:2017-06-12 20:29:44
【问题描述】:

我尝试使用 PwerShell Rename-Item cmdlet 重命名文件。代码如下

Get-ChildItem -recurse * `
  | ?{!$_.PsIsContainer} `
  | Rename-Item -NewName {$_.FullName -Replace '.abcd@email.com','.abcd@email_A.com.abcd@email_B.com.abcd@email_E.com'}

但是,PowerShel 告诉我有关长路径或文件名的信息;这与我的过程无关。但强烈需要保留新的长名称。

如何排除这个错误?

【问题讨论】:

  • -NewName 应该是 string (但 {}indicate a ScriptBlock)使用类似-NewName $($_.FullName -Replace '.abcd@email.com','.abcd@email_A.com.abcd@email_B.com.abcd@email_E.com')
  • 嗨!谢谢你的答案。如果我确实像您提到的那样,我会收到错误消息:“重命名项目:无法将参数绑定到参数 'NewName',因为它为空。”
  • @JosefZ 参见blogs.msdn.microsoft.com/powershell/2006/06/23/…“ScriptBlock 参数”部分 - 将脚本块作为未指定脚本块类型的参数传递是有效的,它将被动态评估。
  • Get all files in folder including those with long (>256 characters) path + name 的可能重复 - 如果不是直接重复,这是许多“长路径错误”问题之一,这有一些链接。简短的回答:没有简单的方法解决它。长答案:您调用较低级别的 API、自定义模块,或安装最新的 Windows 10 并编辑注册表
  • 重命名一个项目意味着它保留在同一个文件夹中,所以不要使用$_.FullName,而是使用$_.Name更改名称。否则使用已建议的 Move-Item。

标签: powershell rename-item-cmdlet


【解决方案1】:

是否可以向您询问代码示例?以下注释代码 sn-p(保守方法)可能会有所帮助:

Get-ChildItem -recurse * | Where-Object {!$_.PsIsContainer} | 
  ForEach-Object {
    ###  in regular expression:  ↓           ↓   escape dots
    $NewName = $_.Name -Replace '\.abcd@email\.com',
      '.abcd@email_A.com.abcd@email_B.com.abcd@email_E.com'

    ### here is right place to check target filename length:
    $targetLength = 1 + $_.DirectoryName.Length + $NewName.Length

    Rename-Item -Path $_.FullName -NewName $NewName
  }

阅读Rename-Item 参考和Regular Expression Language - Quick Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2017-01-12
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多