powershell - 如何修复工作脚本以便能够在多个目录中使用它?
问题描述
首先让我说这个地方是一个很好的资源,它帮助我开发了一个运行良好的脚本,我正在考虑扩展它,但我在这样做时遇到了一些麻烦。
因此,基本上我能够根据这些年份的年份和月份将包含日志文件的目录组织到多个目录中。当我指向那些目录目录时,我可以这样做。
我要做的是将这些脚本应用于多个目录,基本上是(每个)多个目录中的数百个日志,但所有这些目录都在一个主目录中。
我尝试使用 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
}
解决方案
因此,您有一个循环来获取所有目标文件夹,您只需将脚本的其余部分包含在该循环中,并根据它在循环中进行一些修改。
foreach($folder in (Get-ChildItem '\\drive\software\logstoreage\directories' -Directory)){
#--------
# Creation of an "Archive" folder within the root directory of the targeted dir.
# Comments: Archives Folder is created in each targeted directory.
#--------
$ArchiveFolder = New-Item -ItemType directory -Path ($folder.fullname+"\Archive") -Force
#--------
# 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
$files = Get-ChildItem $folder -Recurse -File | where {$_.lastwritetime -lt $date -and !$_.PsIsContainer}
$files
$targetPath = $ArchiveFolder.FullName
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
}
}
推荐阅读
- python - Pytorch 中的“unsqueeze”是做什么的?
- c# - WinForm App未将日志写入LinqPad中数据源时创建的文件
- google-apps-script - 尝试在没有 for 循环的范围内执行 setValue 操作(GoogleAppsScripts)
- c# - 协程在 WaitForSeconds 期间执行代码
- r - 从长格式数据帧构建节点和边
- date - Extjs如何刷新当前时间
- r - R - 如果它们共享相同的行名,如何通过将每个元素中的所有数字相加来连接列表
- r - 是否有从多个数据集中获取多个列中的计数的函数?
- ruby-on-rails - 关于 ruby on rails 搜索页面中 where 方法的问题
- typescript - 不满足打字稿中的约束“对象”