首页 > 解决方案 > 如何防止 PowerShell -Recurse 两次重命名第一个文件?

问题描述

当使用 powershell 用它们的目录名和文件名重命名文件时,我的代码可以工作,除了在目录中的第一个文件中,它给它两个目录名副本。所以文件book1.xlsx夹中的文件folder1应该变成folder1book1.xlsx但它变成了folder1folder1book1.xlsx. 中的其余文件folder1已正确命名为folder1book2.xlsx,folder1book3.xlsx等。

我有一个目录,里面有很多子目录。在每个子目录中都有需要添加其子目录名称的文件。

我一直在关注这段代码。对我来说,它看起来像:

dir -Filter *.xlsx -Recurse | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}

我也试过

--设置Recurse -Depth 1它不会一直在子文件夹中寻找文件夹。

--在管道ForEach-Object {$_ | ...之后使用,与类似。

--在 Visual Studio Code 中而不是直接在 PowerShell 中运行它,这会将其变成:

Get-ChildItem "C:\my\dir\here" -Filter *.xls -Recurse | Rename-Item -NewName {$_.DirectoryName + '_' + $_.Name}

--在子目录中放置一个空文件夹,设置-Depth 2看是否会“捕获”递归循环

我希望这些文件被命名为folder1_book1.xlsx, folder1_book2.xlsx, folder1_book3.xlsx.

但是上面所有尝试的更改都给出了相同的结果。第一个文件被命名为folder1_folder1_book1.xlsx[INCORRECT]、folder1_book2.xlsx[CORRECT]、folder1_book3.xlsx[CORRECT]。

一种解决方法可能是按照此处的建议if为“不包含子目录名称的文件”编写语句。但是该链接搜索文本字符串而不是对象(可能不是正确的术语),例如. 这篇文章展示了如何连接对象,而不是像. 如果按应有的方式工作,则必须放入 if 语句似乎是不必要的步骤,因此我不确定此解决方法是否成为问题的核心。@_.Directory.Name@_.Directory.Name-Recurse

我在 2018 iMac 上运行带有 bootcamp 的 Windows 10(我经常使用 Windows,因为我使用 ArcMap)。电源外壳 5.1.17134.858。Visual Studio 代码 1.38.0。这是我将来想学习如何使用更多的任务,因此解释会有所帮助。我是使用 PowerShell 的新手。提前致谢!

标签: powershellrecursionbatch-rename

解决方案


这是我为我的一位客户创建的脚本,可能会有所帮助

<################################################ ################################################# ###############################

此脚本可用于搜索文件夹以将文件从其原始名称重命名为“filename_foldername.extension”。要使用此脚本,请配置下列项目。

要配置的项目 -$Original -$Source -$Destination -$Files

也请将第 29 行的 Out-File 日期更改为今天的日期****例如:2019-10-02****

我们还添加了一个名为“FileChange.txt”的更改日志文件,可以在第 30 行标识的位置找到

>

$Original="C:\temp\test" #Location of ".cab" files copied
$Source="C:\temp\Test" #Location were ".cab" files are stored
$Destination="C:\temp\Test\2019-10-02" #Location were you want to copy ".cab" files after the file name change. Be sure to change the date to the date you run this script. The script creates a folder with todays date
$Files=@("*.cab") #Choose the file type you want to search for
$ErrorActionPreference = "SilentlyContinue" #Suppress Errors

Get-ChildItem $Original -Include "*.cab" -File -Recurse | Rename-Item -NewName {$_.BaseName+"_"+$_.Directory.Name +'.cab'}
New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd'))"; Get-ChildItem -recurse ($Source) -include ($Files) | Copy-Item -Destination ($Destination) -EA SilentlyContinue
Get-ChildItem $Original | Where {$_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10)} | Out-File C:\temp\test\2019-10-02\FileChange.txt

推荐阅读