下午好,
我需要创建一个脚本来从服务器上所有用户的下载文件夹中删除超过 30 天的文件。
我使用了下面的命令,但没有效果。知道哪里出了问题吗?
Get-ChildItem "\\ server \ folder1 \ User_Data \ * \ Downloads \ *" -Recurse |
Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} |
Remove-Item -ErrorAction SilentlyContinue
答案1
那么,如果你这样做,会发生什么……?
Get-ChildItem 'D:\Test\Reference\New folder' -Recurse
<#
# Results
Directory: D:\Test\Reference\New folder
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 06-Mar-20 10:52 New folder (2)
-a---- 10-Jan-20 17:59 0 awél.txt
-a---- 04-Jan-20 02:01 39 hello.bat
-a---- 04-Jan-20 01:43 44 hello.ps1
-a---- 04-Jan-20 02:16 64 mytest - Copy.txt
-a---- 04-Jan-20 02:16 64 mytest.txt
Directory: D:\Test\Reference\New folder\New folder (2)
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-Jan-20 17:59 0 awél.txt
-a---- 04-Jan-20 02:01 39 hello.bat
-a---- 04-Jan-20 01:43 44 hello.ps1
-a---- 04-Jan-20 02:16 64 mytest - Copy.txt
-a---- 04-Jan-20 02:16 64 mytest.txt
#>
Get-ChildItem 'D:\Test\Reference\New folder' -Recurse |
Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-1))} |
Remove-Item -WhatIf
<#
# Results
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\awél.txt".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\hello.bat".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\hello.ps1".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\mytest - Copy.txt".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\mytest.txt".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\New folder (2)\awél.txt".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\New folder (2)\hello.bat".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\New folder (2)\hello.ps1".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\New folder (2)\mytest - Copy.txt".
What if: Performing the operation "Remove File" on target "D:\Test\Reference\New folder\New folder (2)\mytest.txt".
#>
Get-ChildItem 'D:\Test\Reference\New folder' -Recurse |
Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-1))} |
Remove-Item -Confirm:$false -Force
Get-ChildItem 'D:\Test\Reference\New folder' -Recurse
<#
# Results
Directory: D:\Test\Reference\New folder
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 06-Mar-20 10:51 New folder (2)
#>
答案2
这样效果会更好:
$Path = "\\server\folder1\User_Data\*\Downloads"
$Daysback = "-30"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item