使用powershell脚本将文件名重命名为下一个增量数字 [英] Renaming a file name to the next incremental number with powershell script

查看:59
本文介绍了使用powershell脚本将文件名重命名为下一个增量数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 powershell 脚本的问题.我有一个日常任务调度程序,它导出名为 12122_000000.txt 的文件并将其存储在 C:\ 驱动器上.我在 C:\Report 也有另一个 Report 文件夹.在那个 Report 文件夹中,我有很多名为 12122_000001.txt、12122_000002.txt、12122_0000003.txt、12122_0000004.txt 等等的文件.

I have a question with powershell script. I have a daily task scheduler and it exports the file with the name 12122_000000.txt and store it on C:\ drive. I'm also have another Report folder at C:\Report. In that Report folder, I have a lot of file with the name 12122_000001.txt, 12122_000002.txt, 12122_0000003.txt,12122_0000004.txt and so forth.

我想要一个脚本来检查报告文件夹以查找最新的文件名.然后,将C:\上的文件名12122_000000.txt移动到C:\Report,重命名为最高的名字加1.文件名的格式必须是12122_xxxxxx.txt

I would like to have a script that will check the Report folder to find the latest file name. Then, moving the file name 12122_000000.txt on C:\ to C:\Report and rename it with the highest name increase 1. The format of filename must be 12122_xxxxxx.txt

我尝试编写脚本,但没有成功.请帮助我获得有关 powershell 的知识.

I have tried to write the script but it didn't work. Please help me to gain my knowledge of powershell.

$SourceFile = "C:\12122_000000.txt"
$DestinationFolder = "C:\Report"
if (Test-Path $SourceFile)
{ 
$latest = Get-ChildItem -Path $DestinationFolder| Sort-Object Name -Descending | Select-Object -First 1
$i = 1
Move-Item -path $SourceFile -destination $latest.basename + $i++ + ".txt")
}

谢谢

推荐答案

这里有一个简单的方法来增加这个文件名并移动文件:

Here is an easy way to increment this filename and move the file:

$SourceFile = "C:\12122_000000.txt"
$DestinationFolder = "C:\Report"
if (Test-Path $SourceFile)
{ 
    $latest = Get-ChildItem -Path $DestinationFolder| Sort-Object Name -Descending | Select-Object -First 1
    #split the latest filename, increment the number, then re-assemble new filename:
    $newFileName = $latest.BaseName.Split('_')[0] + "_" + ([int]$latest.BaseName.Split('_')[1] + 1).ToString().PadLeft(6,"0") + $latest.Extension
    Move-Item -path $SourceFile -destination $DestinationFolder"\"$newFileName
}

这篇关于使用powershell脚本将文件名重命名为下一个增量数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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