0

我很想了解在文件夹和子文件夹中回显文件并生成说明文件名的输出的可能方法,这些文件名被拾取以删除 X 天前的文件。

我想在两个不同的层次上写这个脚本

级别 1:PowerShell 脚本仅用于回显文件名并为我提供已确定要删除的文件的输出。这应该包括文件,包括文件夹和子文件夹。

Level2:通过添加删除功能组合level1脚本,这将删除文件夹和子文件夹中的文件。

我有一个要删除的移动脚本和一个直接脚本,但我想确保选择了正确的文件,并且我想知道正在删除的文件名。

非常感谢任何帮助。

编辑从评论中添加

我一直在以一种非常简单的方式尝试这样的事情

Get-ChildItem -Path c:\test | where {$_.lastWriteTime -lt (Get-Date).addDays(-60)} 

我想添加一些参数,它会在不同的文件夹位置生成文件名的输出。

4

2 回答 2

1

我认为这符合您的需求,我向您介绍了一些您可能不知道的概念,例如cmdletbinding,它允许您使用 -whatif 参数来干运行脚本。您还可以提供 -verbose 以查看沿途发生的情况,此时您还可以使用Add-Content cmdlet 附加到日志。

所以你可以这样运行它:

.\DeleteOldFiles.ps1 -Path c:\test -Age 50 -WhatIf -Verbose

然后,当您准备好删除文件时,您可以在没有 -WhatIf 参数的情况下运行它:

.\DeleteOldFiles.ps1 -Path c:\test -Age 50 -Verbose

这并不能回答您的所有问题,但应该可以帮助您入门,我在代码中添加了大量注释,因此您应该能够全部遵循。

# Add CmdletBinding to support -Verbose and -WhatIf 
[CmdletBinding(SupportsShouldProcess=$True)]
param
(
    # Mandatory parameter including a test that the folder exists       
    [Parameter(Mandatory=$true)]
    [ValidateScript({Test-Path $_ -PathType 'Container'})] 
    [string] 
    $Path,

    # Optional parameter with a default of 60
    [int] 
    $Age = 60   
)

# Identify the items, and loop around each one
Get-ChildItem -Path $Path | where {$_.lastWriteTime -lt (Get-Date).addDays(-$Age)} | ForEach-Object {

    # display what is happening 
    Write-Verbose "Deleting $_ [$($_.lastWriteTime)]"

    # delete the item (whatif will do a dry run)
    $_ | Remove-Item
}
于 2013-02-19T18:32:27.487 回答
0

这个问题有点模糊,但我认为这就像你想要的。
我喜欢大卫马丁的回答,但根据您的技能水平和需求,它可能有点过于复杂。

param(
    [string]$Path,
    [switch]$LogDeletions
)

foreach($Item in $(Get-ChildItem -Path $Path | where {$_.lastWriteTime -lt (Get-Date).addDays(-60)}))
{
    if($LogDeletions)
    {
        $Item | Out-File "C:\Deleted.Log" -Append
    }
    rm $Item
}
于 2013-02-19T19:48:05.930 回答