首页 > 解决方案 > 在 Powershell 中移动文件

问题描述

使用下面的代码作为基础(来自另一个问题)我如何在 2 个日期之间移动文件,例如:>2wks AND < 13 Months 到另一个位置。是否可以限制要移动的文件扩展名?

get-childitem -Path "E:\source" |
    where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} | 
    move-item -destination "F:\target"

标签: powershellfilemoveperiod

解决方案


Get-ChildItem可以通过多种方式限制要获取的文件。首先是使用-Filter参数:

# set up the start and end dates
$date1 = (Get-Date).AddDays(-14)
$date2 = (Get-Date).AddMonths(-13)

# using -Filter if you want to restrict to one particular extension.
Get-ChildItem -Path "E:\source" -Filter '*.ext' |
    Where-Object {$_.LastWriteTime -lt $date1 -and $_.LastWriteTime -gt $date2} | 
    Move-Item -Destination "F:\target"

如果您需要限制多个扩展名,则无法使用该-Filter参数执行此操作。相反,您需要使用-Include可以采用通配符模式数组的参数。
请注意,为了使-Include工作,您还必须使用-Recurse开关,或者具有这样的Get-ChildItemend路径\*

# using -Include if you want to restrict to more than one extensions.
Get-ChildItem -Path "E:\source\*" -Include '*.ext1', '*.ext2', '*.ext3' |
    Where-Object {$_.LastWriteTime -lt $date1 -and $_.LastWriteTime -gt $date2} | 
    Move-Item -Destination "F:\target"

然后有一个-Exclude参数,它-Include也接受一个通配符参数的字符串数组,这些参数将过滤掉你不想要的扩展。

如果您需要过滤文件属性,例如 ReadOnly、Hidden 等,您可以使用该-Attributes参数。

对于这些,请查看文档


推荐阅读