Powershell:复制和修改文件名



我需要根据分钟将文件从网络驱动器复制到本地驱动器。复制后,我需要按照以下要求修改文件名:

示例文件名:

Ser1-PRD-CL4$Entreprise_AG2_MyCompany-NA_DB_Name_02_LOG_20191217_094501.trn

  1. 将 35 分钟前创建的所有文件从网络目录复制,例如 \服务器\路径到本地目录 D:\NameofDB (我能够实现复制部分,但想知道我是否应该放置任何标志以防止再次复制同一文件,复制的文件将修改其名称,因此不确定我们如何跟踪它(
  2. 复制
  3. 后,修改所有仅复制文件的名称,如下所示:

    a. 删除单词"MyCompany"之前出现的所有字符

    b. 删除下划线以及单词 LOG "_LOG">

    c. 删除日期和交易编号之间的下划线 (_(:20191217_094501

我已经实现了从文件名中复制和删除"_LOG",但在剩余要求方面遇到了问题。

任何意见将不胜感激:

重要说明:目标中将有其他文件已移动名称,并在目标目录中修改其名称,不应修改这些文件名。

$Sourcefolder= "D:Temp"
$Targetfolder= "D:Temp2"
Get-ChildItem -Path $Sourcefolder -Recurse|
Where-Object {
$_.LastWriteTime -gt [datetime]::Now.AddMinutes(-60)
}| Copy-Item -Destination $Targetfolder
Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name -replace "_LOG", ""} 
Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name -replace '^MyCompany'} #This is not working

有关重复复制相同文件的第一个问题,请参阅: Powershell 脚本可以记录已扫描的文件并在下次运行时忽略它们?

对于 2a(

Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name.substring($_.Name.indexof("MyCompany"))}

请注意,字符串区分大小写。

你可以试试这个:

get-childitem-path "\serversharepath" -recurse | foreach {
if ($_.LastWriteTime -gt [DateTime]::NowAddMinutes(-60)) {
$TheName = $_.Name -replace "_LOG", ""
$TheName = $TheName -replace "d_d", "$1$2"
$TheName = $TheName -replace ".*MyCompany", "MyCompany"
Copy-Item -path $_ -destination {join-path "TargetPath" $TheName}
}
}

您可以在复制时使用 Copy-Item 在复制指定新名称(因此之后无需重命名(。 查看下面的代码以了解想法:

$Sourcefolder= "D:Temp"
$Targetfolder= "D:Temp2"
Get-ChildItem -Path $Sourcefolder -Recurse |
Where-Object {
$_.LastWriteTime -gt [datetime]::Now.AddMinutes(-60)
} | ForEach-Object {
$newname = $_.Name.Replace('_LOG','')                       # removes _LOG  
$newname = $newname -Replace "(d)_(d)","$1$2"             # replace underscore between the digits
$newname = $newname -Replace "(.*)Mycompany","MyCompany$1"  # gets rid of anything before the word "MyCompany"
Copy-Item -Path $_ -Destination (Join-Path $Targetfolder $newname)
}

我在这里尝试使用正则表达式向前看和向后看 https://www.regular-expressions.info/lookaround.html,所以-replace只删除实际匹配的部分。

dir | 
copy-item -destination { 
$_.name -replace '.*(?=MyCompany)' -replace '_LOG' -replace '(?<=d)_(?=d)' } -whatif
What if: Performing the operation "Copy File" on target 
Item:        /Users/js/foo/MyServer$Entreprise_AG2_MyCompany-NA_DB_Name_LOG_20191217_094501.trn 
Destination:                         /Users/js/foo/MyCompany-NA_DB_Name_20191217094501.trn".

最新更新