所以我有一个文件夹目录,我想移动到另一个区域,而且我只想移动30天前创建的文件夹或更多的文件夹。我有一个脚本,做我需要的文件,但它似乎不适用于文件夹。脚本如下
用于移动文件的脚本
param (
[Parameter(Mandatory=$true)][string]$destinationRoot
)
$path = (Get-Item -Path ".\").FullName
Get-ChildItem -Recurse | ?{ $_.PSIsContainer }
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
Foreach-Object {
$content = $path + "\" + $_.Name
$year = (Get-Item $content).LastWriteTime.year.ToString()
$monthNumber = (Get-Item $content).LastWriteTime.month
$month = (Get-Culture).DateTimeFormat.GetMonthName($monthNumber)
$destination = $destinationRoot + "\" + $year + "\" + $month
New-Item -ItemType Directory -Force -Path $destination
Move-Item -Path $content -Destination $destination -force
}Get- should部分似乎不像它应该的那样拉目录。
发布于 2018-11-12 15:47:27
所以看剧本,我决定改变一些事情
Function Move-FilesByAge(){
param (
[Parameter(Mandatory=$true)][string]$Source,
[Parameter(Mandatory=$true)][string]$Destination,
[Parameter(Mandatory=$true)][timespan]$AgeLimit
)
Get-ChildItem $Source -Directory -Recurse | ?{
$($_.CreationTimeUtc.Add($AgeLimit)) -lt $((Get-Date).ToUniversalTime())
} | %{
$Dpath = $Destination + "\" + $_.CreationTimeUtc.ToString("yyyy") + "\" + $_.CreationTimeUtc.ToString("MMMM")
New-Item -ItemType Directory -Force -Path $Dpath
Move-Item $_ -Destination $Dpath -Force
}
}
Move-FilesByAge -Source C:\Test -Destination C:\Test2 -AgeLimit (New-TimeSpan -days 30)这可能导致一个重大问题。如果存在同名文件夹,则会弹出该文件夹存在的错误。
由于您是powershell新手,所以让我们介绍一下有关这个脚本的一些基础知识。在Powershell中,我们喜欢管道|,您在原始版本中做得很好。我们也是别名的忠实粉丝,其中对象?{},Foreach-Object %{}。
获取-儿童有一个内置的开关,只返回目录-directory。
您还在使用上一次LastWriteTime,而应该使用CreationTime。CreationTimeUtc允许您通过提供基本时区来标准化跨时区的时间。
Date.ToString(这里的日期格式)。是缩短将日期解析为字符串的好方法。.ToString("yyyy")给你带来了像2018年这样的4个数字。.ToString("MMMM")将以三月的名字来命名这个月。
https://stackoverflow.com/questions/53264748
复制相似问题