Powershell根据上次修改日期复制文件,然后重命名它们



我的powershell脚本有点卡住了。

我想浏览多个文件夹,根据上次修改的日期抓取文件,并将其复制到新位置。在那里,我必须根据它的原始文件名将它们重命名为特定的约定。我写的内容只贯穿了第一部分,并成功地复制了文件,但之后没有重命名它们。当然,当我第二次运行脚本时,它会重命名文件。。。

文件约定为:120_00001_000_00222_202201_20220124_121833_形式-Copy.pdf

结果应该是2222_120_记忆01-2022 _012022.pdf

这是我已经得到的

$path = "G:Temp"
$Target = "K:Local"
$Max_days = "-60" #Max Days past
$Curr_date = Get-Date
$files = get-childitem $Target *.pdf

Get-ChildItem -Path $path -Recurse -Filter 120_*.pdf |
Where-Object {
$_.LastWriteTime `
-gt (Get-Date $Curr_date.AddDays($Max_days)) `
} | ForEach-Object { $_ | Copy-Item -Destination $Target  -Force -PassThru } 
foreach($pdf in $files)
{
$split = $pdf.name -replace ".pdf" -split "_"
$newname = "$($split[3].TrimStart("0"))_$($split[0])_$("Memory") $($split[4].Substring($split[4].Length - 2, 2))-$($split[5].Substring(0,4))_$($split[4].Substring($split[4].Length - 2, 2))$($split[5].Substring(0,4))$($pdf.Extension)"
write-verbose "Original: $($pdf.name)" -verbose
write-verbose "NewName: $($newname)" -verbose
Rename-Item $pdf.FullName -NewName $newname -verbose 
}

感谢Adavned

对问题进行了更精确的编辑。

如前所述,您可以在一个循环中完成此操作,并在复制时重命名文件。

试试下面的:

$path     = 'G:Temp'
$Target   = 'K:Local'
$Max_days = -60   # Max Days in the past
$refDate  = (Get-Date).AddDays($Max_days).Date  # set to midnight
# get the files of interest
Get-ChildItem -Path $path -Recurse -Filter '120_*_*_*_*_*_*_*.pdf' -File |
Where-Object { $_.LastWriteTime -gt $refDate } | 
ForEach-Object { 
# rename the file to match the new file naming convention
$split = $_.BaseName -split "_"
# just for clarity, using this example: 
# '120_00001_000_002222_202201_20220124_121833_Formular - Copy.pdf'
# $split[0]  --> 120                used unchanged
# $split[1]  --> 00001              unused
# $split[2]  --> 000                unused
# $split[3]  --> 002222             used without leading zeros
# $split[4]  --> 202201             used, only the last two digits (month)
# $split[5]  --> 20220124           used, only the first four digits (year)
# $split[6]  --> 121833             unused
# $split[7]  --> Formular - Copy    unused
# these elements are used more than once, so for convenience store in separate variables
$month = $split[4].Substring($split[4].Length - 2, 2)
$year  = $split[5].Substring(0,4)
# construct the new file name
$newName = '{0}_{1}_Memory {2}-{3}_{2}{3}{4}' -f $split[3].TrimStart("0"),
$split[0],
$month,
$year,
$_.Extension
# construct the complete target path and filename
$targetFile = Join-Path -Path $Target -ChildPath $newName
# now copy the file with a new name to the target folder
$_ | Copy-Item -Destination $targetFile -Force
}

我使用了-f格式操作符来构造新的文件名,因为我相信这会使代码更容易阅读。

我没有考虑到可能会发生命名冲突(目标文件夹中已经有新名称的文件(
如果发生这种情况,您需要告诉我们要使用什么策略
也许可以像Windows那样在文件的方括号中附加一个索引号?

相关内容

最新更新