我正在尝试创建一个执行以下操作的脚本:
1)检查MASTERFOLDER内部的所有子文件夹/文件
2)所有文件都具有相同的扩展名,并且在同一天进行了修改
Script to Create a Monthly folder and move files to it every month。
代码基于上面的问题:
# Get the files which should be moved, without folders
$files = Get-ChildItem '\\test\d$\Reports\client *' -Recurse |
where {!$_.PsIsContainer}
# List Files and names which will be moved
$files.names
# Target Folder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = '\\test\d$\Reports\client\'
foreach ($file in $files)
{
# Get year and Month of the file
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString("00")
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)
LastWriteTime无法正常工作-文件必须根据包含日期的名称进行排序-例如: ClientReportX 20191014 file1.csv
也许每年都使用-match为2015-2019 +几个月
$filesstructure| foreach-object (file in files) {
if($file.name-match '2019') {
#MOVE TO FOLDER 2019 - > MONTH OF FILE
ELSE($filename -match '2018' {
#MOVE TO FOLDER 2018 -> MONTH OF FILE
.....
其余代码
# Set Directory Path
$Directory = $targetPath + "\" + $month + $monthname
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
$file | Move-Item -Destination $Directory
}
目标:主文件夹> 2019-2015年每年的子文件夹列表。每个文件夹年内> 1月-12月。
感谢您的帮助
答案 0 :(得分:1)
您可以使用.Substring()从文件名中取出年,月和日,如下所示。之后,您可以创建一个新的DateTime对象并接收月份名称。
$FileName = 'ClientReportX 20191014 file1.csv'
$Year = $FileName.Split(' ')[1].Substring(0, 4)
$Month = $FileName.Split(' ')[1].Substring(4, 2)
$Day = $FileName.Split(' ')[1].Substring(6, 2)
$MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'
希望日期总是采用相同的格式...此示例使用正则表达式(About Regular Expressions)和自动$ Matches Hashtable变量来检索捕获的文本。
$FileName = 'ClientReportX 20191013 file1.csv'
if ($FileName -match '([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))') #Check with regex if date is in file name
{
$DateFromFileName = $Matches[0] #$Matches is a default variable (Hashtable) and the matches will be stored here
$Year = $DateFromFileName.Substring(0, 4)
$Month = $DateFromFileName.Substring(4, 2)
$Day = $DateFromFileName.Substring(6, 2)
$MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'
$MonthName
}
$Matches.Clear() #Clear the match