【问题标题】:How to replace a special character from a file name in a document in PowerShell如何从 PowerShell 文档中的文件名中替换特殊字符
【发布时间】:2020-07-14 02:29:06
【问题描述】:

我正在尝试通过文件夹中的几个文档运行 PowerShell 脚本,并替换任何可能包含某些特殊字符(主要是 $、#)的文档。但我想同时做这两件事。

$files1 | ForEach-Object {Rename-Item $_ ($_.FullName -replace "#", "")}

目前我收到以下错误

重命名项目:找不到驱动器。名为“@{FullName=F”的驱动器不存在。在第 2 行 char:3 + Rename-Item $_ ($_.FullName -replace "#", "")

files1 变量的输出是这样的

全名:F:\baggy\17_10_27 可能会放弃 - dondeal - EPT 2337 jonney - 关闭 #025-17.msg 父文件夹:F:\baggy\ 全路径长度:108 扩展名:味精 名称:17_10_27 可能放弃 - dondeal - EPT 2337 jonney - 关闭 #025-17.msg 长度:121344 最后写入时间:2017 年 10 月 27 日下午 1:43:02 全名:F:\baggy\17_10_27 Crickey 豁免鼓天际线未水泥 - #068-17 rewax RX - 重新发送至 OOE.msg 父文件夹:F:\baggy\ 全路径长度:106 扩展名:味精 名称:17_10_27 Crickey 豁免鼓天际线未水泥 - #068-17 rewax RX - 重新发送至 OOE.msg 长度:386560 最后写入时间:2017 年 10 月 27 日下午 4:16:23

【问题讨论】:

    标签: powershell powershell-3.0


    【解决方案1】:

    试试这个:

    $files1 | ForEach-Object {Rename-Item $_.FullName ($_.FullName -replace "#", "")}
    

    但是,如果您不移动文件,我建议:

    $files1 | ForEach-Object {Rename-Item $_.FullName ($_.Name -replace "#", "")}
    

    【讨论】:

    • 谢谢,这两个答案都对我有用。最后一个问题,有没有办法在替换字符时包含子文件夹?我尝试使用'-recurse',但我收到此错误"Rename-Item : Source and destination path must be different."
    【解决方案2】:

    这应该可以解决问题:

    Get-ChildItem -Path X:\path-you-want | Rename-Item {$_.FullName -replace '#' -replace '$'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多