您可以帮我修改此脚本吗?
我有一个带有几个子文件夹的根文件夹
c:// root / many-subfolders / many-logfiles。
我想让sctipt对年/月的长文件进行排序,并输出到原始子文件夹,不包括当年的文件
c:// root / many-subfolders / year / month / logfiles
$Filepath = ""
$file = ""
$date = ""
$month = ""
$year = ""
$MonthPath = ""
$FilePath = Read-Host "Place the directory which contains the files."
Write-Warning "Note: This action can take several minutes, depending on the amount of files in $FilePath."
Get-ChildItem $FilePath | % {
$file = $_.FullName
$date = Get-Date ($_.LastWriteTime)
$month = $date.Month
$year = $date.Year
$MonthPath = "$FilePath\$year\$month"
Write-Verbose "month = $month"
Write-Verbose "Date = $date"
Write-Verbose "year = $year"
Write-Verbose "FilePath = $FilePath"
Write-Verbose "Filename = $file"
Write-Verbose "MonthPath = $MonthPath"
if (!(Test-Path -Path "$MonthPath" )) {
Write-Verbose "Creating log location $MonthPath."
#Write-Host -BackgroundColor green -ForegroundColor black "Creating log location $MonthPath."
Write-Verbose "MonthPath inside path test = $MonthPath"
New-Item -ItemType Directory -Path $MonthPath | Out-Null
} else {
#Write-Host -BackgroundColor green -ForegroundColor black "Log location exists already exist $MonthPath"
Write-Verbose "Log location exists already exist $MonthPath"
}
Move-Item "$file" "$MonthPath" | Out-Null
}
Write-Warning "All files are sorted now based upon year and month."
答案 0 :(得分:0)
据我了解,您需要过滤c:\ root \中的所有文件,然后将它们移至新目录。
# Set the $Filepath you are going to search for the files, if you have a specific extension you may filter that for better results and performance.
$FilePath = "C:\setup\testlogs"
# Put all the files to an variable with some of their attributes you may need the CreationTime or the LastWriteTime depends on what you need!!!!
$AllFiles = Get-ChildItem -Path C:\Setup\TestLogs -File -Recurse |select Name, FullName, CreationTime, LastWriteTime
Foreach ($File in $AllFiles)
{
# Put an if with less than the date you want the logs to be moved.
If ($File.LastWriteTime -lt "11/07/2018")
{
Write-Host "The file is ready for archive"
$Date = Get-Date ($File.LastWriteTime) -Format dd/MM/yyyy
$Month = $File.LastWriteTime.Month
$Year = $File.LastWriteTime.Year
$NewPath = "$FilePath\$year\$month"
$CheckExist = Test-Path $FilePath\$year\$month
# Check if the path already exist and move the file to the folder Else create the new folder and move the file there
If ($CheckExist -eq $true)
{
Move-Item -Path $File.FullName -Destination $FilePath\$year\$month\
}
Else
{
New-Item -Path $Filepath\$year\$month -ItemType Directory
Move-Item -Path $File.FullName -Destination $FilePath\$year\$month\
}
}
Else
{
Write-Host "The File is not that old to be archived"
}
}
我希望这就是您想要的!
让我知道,以便为您解决问题提供更多帮助。