循环浏览子文件夹以重命名Powershell中的文件 [英] Cycle through sub-folders to rename files in Powershell

查看:48
本文介绍了循环浏览子文件夹以重命名Powershell中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件目录,其中包含许多文件夹.在每个子文件夹中,我都有各种文件.我想浏览每个文件,重命名一些项目,并为其中一些添加扩展名.我正在使用Powershell来做到这一点.

I have a file directory that contains many folders within it. Inside each of these sub-folders, I have a variety of files. I would like to go through each file, rename some of the items, and add extensions to some of them. I am using Powershell to do this.

我的文件名带有.".必须全部替换为"_",例如,"wrfprs_d02.03"应为"wrfprs_d02_03".我能够使用以下代码在一个文件夹中成功完成此操作:

I have file names with "." that all need to be replaced with "_" for example, "wrfprs_d02.03" should be "wrfprs_d02_03". I was able to successfully do that in one folder with the following code:

dir | rename-item -NewName {$_.name -replace "wrfprs_d02.","wrfprs_d02_"}

之后,我进行了替换,我想在某些文件上添加.grb扩展名,这些扩展名恰好以"w"开头,并且我能够在一个文件夹中使用以下命令进行此操作:

After, I make those replacements, I want to add .grb extensions on to some of the files, which all happen to start with "w", and I was able to do that within one folder with:

Get-ChildItem | Where-Object {$_.Name -match "^[w]"} | ren -new {$_.name + ".grb"}

当我从一个文件夹中退回并尝试在多个文件夹中迭代地执行此操作时,我的代码不起作用.我在一个名为"Z:\ Windows.Documents \ My Documents \ Test_data \ extracted"的目录中,该目录包含我要迭代的所有子文件夹.我正在使用以下代码:

When I step back from one folder and try to do it iteratively within many folders, my code doesn't work. I am in a directory called "Z:\Windows.Documents\My Documents\Test_data\extracted" which contains all my sub-folders that I want to iterate over. I am using the following code:

$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"}
}

对我的问题有任何想法吗?

Any ideas on what my problem is?

推荐答案

不确定您遇到了什么错误,但是使用重命名项可能很棘手.或者至少以我的经验是这样.

Not sure what error you were getting, but using rename-item can be finicky. Or at least so in my experience.

我毫无疑问地使用了以下内容.我的文件名不同,所以我用下划线替换了所有的句点.如果文件以"W"开头,那么它将更改该文件的扩展名.

I used the follow without issue. My files names were different so I replaced all periods with underscores. If the file starts with "W" then it changed the extension for that file.

$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
    }
 }

希望有帮助.

这篇关于循环浏览子文件夹以重命名Powershell中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆