powershell - 如何防止 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 的新手。提前致谢!
解决方案
这是我为我的一位客户创建的脚本,可能会有所帮助
<################################################ ################################################# ###############################
此脚本可用于搜索文件夹以将文件从其原始名称重命名为“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
推荐阅读
- android - 将多个嵌套列表保存到房间数据库中
- regex - 正则表达式匹配排除其他相似字符串中的特定字符
- python - 如何在 Python 2021 中安装 shapely 包
- python - Pandas groupby 通过指定最小数量的非 NA 值来表示平均值
- find - 使用找到的记录集作为值列表的基础
- html - 为什么 Sublime Text 上下文菜单被禁用(下图)
- reactjs - MultiSelect 在值状态更改时不更新值(PrimeReact UI)
- python - 从 pyplot.plot 动作的循环中获取 ylim - 只有循环寄存器中的最后一个,其他一切都是 0、1
- javascript - 随着 Firebase RTDB 上的数据发生变化,实时更新 Html 表
- azure-devops - 错误找不到工作项类型产品待办事项项