循环通过子文件夹重命名Powershell中的文件
我有一个文件目录,其中包含许多文件夹。在每个这些子文件夹中,我都有各种文件。我想浏览每个文件,重命名一些项目,并为其中一些项目添加扩展名。我正在使用Powershell来做到这一点。循环通过子文件夹重命名Powershell中的文件
我的文件名是“。”例如,“wrfprs_d02.03”应该是“wrfprs_d02_03”。我是能够成功地做到这一点与下面的代码在一个文件夹中:
dir | rename-item -NewName {$_.name -replace "wrfprs_d02.","wrfprs_d02_"}
后,我会把这些替代,我想添加到一些文件.grb扩展,这一切发生下手“ W”,我能够做一个文件夹中有:
Get-ChildItem | Where-Object {$_.Name -match "^[w]"} | ren -new {$_.name + ".grb"}
当我一步从一个文件夹,并尝试多个文件夹内反复这样做,我的代码不能正常工作。我在一个名为“Z:\ Windows.Documents \ My Documents \ Test_data \ extract”的目录中,其中包含我想要遍历的所有子文件夹。我正在使用以下代码:
$fileDirectory = "Z:\Windows.Documents\My Documents\Test_data\extracted"
foreach($file in Get-ChildItem $fileDirectory)
{
dir | rename-item -NewName {$_.name -replace "wrfprs_d02.","wrfprs_d02_"}
Get-ChildItem | Where-Object {$_.Name -match "^[w]"} | ren -new {$_.name + ".grb"}
}
有关我的问题是什么的任何想法?
不知道你得到了什么错误,但使用重命名项目可以是挑剔的。或者至少在我的经验中如此。
我用了以下没有问题。我的文件名称不同,所以我用下划线替换了所有的句点。如果文件以“W”开头,则它改变了该文件的扩展名。
$FilePath = Get-ChildItem "Z:\Windows.Documents\My Documents\Test_data\extracted" -Recurse -File
foreach ($file in $FilePath)
{
$newName = $file.Basename.replace(".","_")
$New = $newName + $file.Extension
if($file.Name -match "^[w]")
{
Rename-Item $file.FullName -NewName "$($New).grb"
}
else
{
Rename-Item $file.FullName -NewName $New
}
}
希望有帮助。
因为当您使用管道时,$ _被替换为循环。我建议你一个新的代码:
$fileDirectory = "Z:\Windows.Documents\My Documents\Test_data\extracted"
Get-ChildItem $fileDirectory -recurse -file -filter "*.*" |
%{
#replace . by _
$NewName=$_.Name.Replace(".", "_")
#add extension grb if name start by w
if ($NewName -like "w*") {$NewName="$NewName.grb"}
#Add path file
$NewName=Join-Path -Path $_.directory -ChildPath $NewName
#$NewName
#rename
Rename-Item $_.FullName $NewName
}
我收到以下错误代码: Get-ChildItem:找不到与参数名称'file'匹配的参数。 – Amelia
你的PowerShell版本是什么? – Esperento57
谢谢!该代码几乎为我工作。由于我正在使用的特定文件,我做了一些修改。我看到文件名称改变“。”到Powershell窗口中的“_”,但是当我打开Windows资源管理器时,这些句点实际上并未改变为下划线。虽然已经添加了扩展,所以该部分已解决! – Amelia
你是对的,我们做了修改,但从未真正保存过这些修改。我现在用一个适当的例子更新它。希望这有助于让我知道,如果没有。 – JonnyBoy