当使用powershell重命名具有目录名和文件名的文件时,我的代码有效,except在目录中的第一个文件中,它为它提供了目录名的两个副本。因此,文件夹book1.xlsx
中的文件folder1
应该变成folder1book1.xlsx
,但它变成folder1folder1book1.xlsx
。 folder1
中的其余文件正确命名为folder1book2.xlsx
,folder1book3.xlsx
等。
我有一个目录,其中包含许多子目录。每个子目录中都有需要添加其子目录名称的文件。
我一直在关注此code。对我来说,它看起来像:
dir -Filter *.xlsx -Recurse | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}
我也尝试过
-设置Recurse -Depth 1
,使其不再在子文件夹中寻找文件夹。
-在管道后使用ForEach-Object {$_ | ...
,类似于this。
-在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
编写as suggested here语句。但是链接会搜索文本字符串,而不是像@_.Directory.Name
这样的对象(可能不是正确的术语)。此post显示了如何串联对象,但没有类似@_.Directory.Name
的东西。如果-Recurse
以应有的方式工作,则必须放入if语句似乎是不必要的步骤,因此我不确定此解决方法是否会成为问题的核心。
我正在2018 iMac上运行带有Bootcamp的Windows 10(由于使用ArcMap,我经常在Windows中使用)。 Powershell 5.1.17134.858。 Visual Studio代码1.38.0。这是我将来要学习如何使用的任务,因此说明会有所帮助。我是使用PowerShell的新手。预先感谢!
这是我为一位客户创建的脚本,可能会有所帮助
此脚本可用于搜索文件夹以重命名文件夹中的文件原始名称为“ filename_foldername.extension”。使用此脚本请配置下面列出的项目。
Congfigure的项目-$原始-$来源-$目的地-$ Files
也请将第29行的出库日期更改为今天的日期****例如: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