简体   繁体   English

用不同的名称重命名多个文件

[英]Renaming multiple files with different names

I am a programmer by no means and am brand new to using powershell, but have been tasked with setting up some batch export processes for daily files we FTP.我绝不是一名程序员,并且对使用 powershell 是全新的,但我的任务是为 FTP 的日常文件设置一些批量导出过程。 I need to come up with a script that will take changing file names and change them within the same directory to new names;我需要想出一个脚本来更改文件名并将它们在同一目录中更改为新名称;

Example: files will come in as below (YYYYMMDD will be the changing variable)示例:文件将如下所示(YYYYMMDD 将是变化的变量)

YYYYMMDD_Share_Support.txt
YYYYMMDD_Person_Support.txt

We need them to be stripped from the above to:我们需要将它们从上面剥离以:

Share.txt
Person.txt

so on and so forth.等等等等。

I have found ways to make this work, but only on an as needed basis for one file at a time with specific names, not names that will change daily.我已经找到了使这项工作的方法,但仅在需要的基础上一次使用一个具有特定名称的文件,而不是每天都会更改的名称。

So far I am using:到目前为止,我正在使用:

Get-ChildItem -Filter *.txt

Dir | %{Rename-Item $_ -NewName ("NEWFILENAME.txt" -f $nr++)}

You could use the regex -replace operator inside a pipeline-bound scriptblock:您可以在管道绑定脚本块中使用 regex -replace运算符:

$files = Get-ChildItem -filter *.txt 
$files |Rename-Item -NewName { $_.Name -replace '^\d{8}_(.*)_Support\.txt$', '$1.txt' }

As suggested by TheIncorrigible1 , if you know the relative position of the word you need, you can also use -split :正如TheIncorrigible1 所建议的,如果您知道您需要的单词的相对 position,您也可以使用-split

$files |Rename-Item -NewName {'{0}.txt' -f ($_.Name -split '_')[-2]}  # grab 2nd last word

How about:怎么样:

dir *.txt | 
  rename-item -newname { $null,$base,$null = $_.basename -split '_'; "$base.txt" } -whatif

Probably a longer version of the answer.可能是答案的更长版本。 An alternative mentioned by @TheIncorrigible1 @TheIncorrigible1 提到的另一种选择

$logDir = "D:\Satish\TestFolders"
cd $logDir

$files = ls

foreach ($file in $files){
$fileSplit=($file.ToString()).split("_")


ren $file "$($fileSplit[1]).txt"

}

And for Share.txt to YYYYMMDD_Share_Support.txt对于 Share.txt 到 YYYYMMDD_Share_Support.txt

$logDir = "D:\Satish\TestFolders"
cd $logDir

$files = ls

$date = Get-Date -Format "yyyyMMdd"

foreach ($file in $files){
$fileSplit=($file.ToString()).split(".")


ren $file "$($date)_$($fileSplit[0])_Support.txt"

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM