简体   繁体   English

使用Powershell递归删除/重命名文件

[英]Recursively removing/renaming files using powershell

I have to go through many levels of child folders and remove special characters that are invalid in SharePoint, mainly '#&' 我必须遍历多个级别的子文件夹,并删除在SharePoint中无效的特殊字符,主要是'#&'

I have scoured the internet trying different commands; 我曾尝试过各种命令来搜寻互联网; rename-item/move-item, variations of the two, all to no avail. 重命名项目/移动项目,两者的变化,都无济于事。 The closest i've gotten is using: 我得到的最接近的是使用:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!@#&]','_'}

but i keep getting this error: Rename-item: Source and destination path must be different. 但我一直收到此错误:重命名项:源路径和目标路径必须不同。

Could someone point me in the right direction? 有人可以指出我正确的方向吗?

Regards 问候

That error only happens when you attempt to rename a directory to the same NewName as the current name, you can safely ignore it. 仅当您尝试将目录重命名为与当前名称相同的NewName时,才会发生该错误,您可以放心地忽略它。

Add -ErrorAction SilentlyContinue to silently suppress the error message: Add -ErrorAction SilentlyContinue以静默方式抑制错误消息:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!@#&]','_'} -ErrorAction SilentlyContinue

You need to filter out the files that you're not planning to rename: 您需要过滤出不打算重命名的文件:

Get-ChildItem -Recurse |
    Where-Object { $_.Name -match '[!@#&]' } |
    Rename-Item -NewName {$_.Name -replace '[!@#&]','_'}

something like this may work 这样的事情可能会起作用

dir -Recurse -File | ? basename -Match '[!@#&]' | % {
    # if the file.txt already exists, rename it to file-1.txt and so on
    $num = 1
    $base = $_.basename -replace'[!@#&]', '_'
    $ext = $_.extension
    $destdir = Split-Path $_.FullName
    $newname = Join-Path $destdir "$base$ext"
    while (Test-Path $newname) {
        $newname = Join-Path $destdir "$base-$num$ext"
        $num++
    }

    ren $_.fullname $newname
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM