在Powershell中相对于当前位置移动项目

时间:2017-11-08 09:36:58

标签: powershell relative-path

我需要遍历一个文件夹(ParentLogFolder),查找日志并将它们从相对文件夹(SUBLOG)移动到子文件夹(CompressedLogFolder)

ParentLogfolder  
---SubLog  
------CompressedLogFolder  
---SubLog  
------CompressedLogFolder

文件夹结构,不限于2个子文件夹,可以是100 +

$Path = "C:\ParentLogFolder"
$Pattern = "*.log"
$date = get-date
$AgeLimit = $date.AddDays(-31)
Get-ChildItem -Filter $Pattern -path $path -recurse | Where-Object 
{$_.LastWriteTime -lt $AgeLimit} | Move-Item -Path

我无法弄清楚如何将父文件夹的文件转换为变量,并将子文件夹作为目标添加到Move-Item部分。

那里有谁可以帮忙回答这个问题?

不要介意代码的$Date部分,它可以正常工作,因为它需要在解决方案中。

1 个答案:

答案 0 :(得分:1)

而不是在线,请考虑强调代码清晰度。也就是说,通过分而治之的方法打破子步骤中的过程。当管道未被过多使用时,更容易检查变量是否存在错误值。像这样,

$allFiles = Get-ChildItem -Filter $Pattern -path $path -recurse
$oldFiles = $allFiles | ? { $_.LastWriteTime -lt $ageLimit }

foreach($file in $oldFiles) {
    $archiveFolder = join-path $file.DirectoryName 'someArchiveFolder'
    $destination = join-path $archiveFolder $file.Name
    move-item -whatif $file.FullName $destination
}

-whatif开关将打印移动命令将执行的操作。删除它以实际移动文件。

相关问题