【发布时间】:2019-03-27 20:20:09
【问题描述】:
首先让我说这个地方是一个很好的资源,它帮助我开发了一个运行良好的脚本,我正在考虑扩展它,但我在这样做时遇到了一些麻烦。
所以,基本上我可以根据这些年份的年份和月份将包含日志文件的目录组织到多个目录中。当我指向那些目录目录时,我可以这样做。
我要做的是将这些脚本应用于多个目录,基本上是(每个)多个目录中的数百个日志,但所有这些目录都在一个主目录中。
我尝试使用 foreach cmdlet 应用脚本,但它似乎不起作用。
#--------
# Creation of an "Archive" folder within the root directory of the targeted dir.
# Comments: Archives Folder is created in each targeted directory.
#--------
foreach($folder in (Get-ChildItem '\\drive\software\logstoreage \directories' -Directory)){
New-Item -ItemType directory -Path ($folder.fullname+"\Archive")
}
#--------
# Organization of Logs into Yearly and Monthly directories.
# Comments: Folders are created based on the Year capturing logs through the end of 2018.
#--------
$date = (Get-Date -Month 1 -Day 1 -Year 2019).ToString("01-01-2019")
$files = Get-ChildItem '\\drive\software\logstoreage\directories\SoftwareA' -Recurse | where {$_.lastwritetime -lt $date -and !$_.PsIsContainer}
$files
$targetPath = '\\drive\software\logstoreage\directories\SoftwareA\Archive'
foreach ($file in $files){
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
$file.Name
$year
$month
$Directory = $targetPath + "\" + $year + "\" + $month
if (!(Test-Path $Directory)){
New-Item $directory -type directory
}
$file | Move-Item -Destination $Directory
}
【问题讨论】:
-
请提供一组目录和日志示例,以及脚本的预期结果。实际上,我猜这不起作用,因为您遍历目录,但实际上除了创建存档文件夹之外什么都不做。您需要扩展该循环以包含脚本的其余部分,而不是硬编码
$targetdirectory或$files =行中的路径。 -
一旦您使用带有
-Directory参数的gci,然后使用gci 和Where-Object检查!$_.PSIsContainer而不是gci 的-File参数?当您使用该 var 与LastWriteTime进行比较时,也不要强制转换$date字符串 -
@TheMadTechnician 例如,我将日志存储在 Logstorage 目录中,这些日志都与属于它们的软件相关联。我有 softwareA、SoftwareB、SoftwareC 等等(我有数百个)。例如:C:\Logstorage\Windows\SoftwareA\log1.csv;当我直接指向目录时脚本有效,但我没有时间一一输入。
标签: powershell subdirectory organization