当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 管理回收站

作者:精品下载站 日期:2024-12-14 07:56:19 浏览:15 分类:玩电脑

使用 PowerShell 管理回收站


不久前,我发布了 Iron Scripter 挑战,要求您编写一些 PowerShell 代码来处理回收站中的项目。系统要求您计算回收站使用了多少空间,然后恢复文件。如果您愿意,请停止阅读这篇文章,查看挑战并看看您能想出什么。如果您陷入困境,这篇文章可能会让您重回正轨。尽管如此,我确信有多种方法可以应对挑战。我的解决方案远不是唯一的解决方案。

解析回收站

我决定使用 COM 对象方法并使用对 Shell.Application 的引用。 Windows 回收站可以作为命名空间 10 进行访问。

$shell = New-Object -com shell.application
$rb = $shell.Namespace(10)

该命名空间将包括所有固定磁盘上的回收站。尽管此对象类型可能没有详细记录,但您仍然可以使用 PowerShell 来了解要执行的操作。 Get-Member 仍然是您的朋友。

[玩转系统] 使用 PowerShell 管理回收站

Items 属性看起来会给我删除的项目。

[玩转系统] 使用 PowerShell 管理回收站

果然确实如此。为了使这更容易,我将把这些项目添加到一个数组中。

[玩转系统] 使用 PowerShell 管理回收站

这就是棘手的地方。

虽然我的回收站里看起来只有 156 件物品,但实际上还有更多。我只看到顶级 156 项。作为文件夹的项目有自己的 Items 属性。

[玩转系统] 使用 PowerShell 管理回收站

正如您所看到的,每个已删除的文件都有很好的信息。在使用 Get-Member 探索对象时,我组合了一个函数,将每个已删除的项目转换为可用的 PowerShell 对象。

Function ParseItem {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [object]$Item
    )
    #this function relies variables set in a parent scope
    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $($item.path)"
        
        # uncomment for troubleshooting
        # $global:raw += $item
        if ($item.IsFolder -AND ($item.type -notmatch "ZIP")) {
            Write-Verbose "Enumerating $($item.name)"
            Try {
                #track the path name through each child object
                if ($fldpath) {
                    $fldpath = Join-Path -Path $fldPath -ChildPath $item.GetFolder.Title
                }
                else {
                    $fldPath = $item.GetFolder.Title
                }
                #recurse through child items
                $item.GetFolder().Items() | ParseItem
                Remove-Variable -Name fldpath
            }
            Catch {
               # Uncomment for troubleshooting
               # $global:rbwarn += $item
                Write-Warning ($item | Out-String)
                Write-Warning $_.exception.message
            }
        }
        else {
            #sometimes the original location is stored in an extended property
            $data = $item.ExtendedProperty("infotip").split("`n") | Where-Object { $_ -match "Original location" }
            if ($data) {
                $origPath = $data.split(":", 2)[1].trim()
                $full = Join-Path -path $origPath -ChildPath $item.name -ErrorAction stop
                Remove-Variable -Name data
            }
            else {
                #no extended property so use this code to attemp to rebuild the original location
                if ($item.parent.title -match "^[C-Zc-z]:\") {
                    $origPath = $item.parent.title
                }
                elseif ($fldpath) {
                    $origPath = $fldPath
                }
                else {
                    $test = $item.parent
                    Write-Host "searching for parent on $($test.self.path)" -ForegroundColor cyan
                    do { $test = $test.parentfolder; $save = $test.title } until ($test.title -match "^[C-Zc-z]:\" -OR $test.title -eq $save)
                    $origPath = $test.title
                }

                $full = Join-Path -path $origPath -ChildPath $item.name -ErrorAction stop
            }

            [pscustomobject]@{
                PSTypename       = "DeletedItem"
                Name             = $item.name
                Path             = $item.Path
                Modified         = $item.ModifyDate
                OriginalPath     = $origPath
                OriginalFullName = $full
                Size             = $item.Size
                IsFolder         = $item.IsFolder
                Type             = $item.Type
            }
        }
    } #process
}

我的函数有一个非标准名称,因为我将它用作控制脚本内的内部辅助函数。我可以使用此函数将每个回收站项目转换为更易于使用的内容。

[玩转系统] 使用 PowerShell 管理回收站

这意味着我可以获得这样的所有物品:

$bin = $rb.items() | ParseItem

这使得计算我的回收站使用了多少空间变得非常容易。

[玩转系统] 使用 PowerShell 管理回收站

有了这段代码作为我的基础,获取不同固定驱动器的回收站信息就不再需要那么多工作了。

$bin | group-object -Property {$_.path.substring(0,2)} |
Select-Object -Property Name,Count,
@{Name="SizeMB";Expression = {($_.group | measure-object -Property size -sum).sum/1MB}}

[玩转系统] 使用 PowerShell 管理回收站

恢复回收站项目

因为我预先完成了所有工作,使用原始位置信息将对象写入管道,所以编写一个函数来通过将已删除的项目从回收站位置移动到原始位置来恢复已删除的项目非常容易。

Function Restore-RecycleBinItem {
    [cmdletbinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [object]$Item
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"

    } #begin

    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] $($Item.Path) "
        if (-Not (Test-Path $Item.originalPath)) {
            New-Item $Item.originalpath -force -itemtype directory
        }
        Move-Item -path $Item.Path -Destination $Item.OriginalFullName -PassThru -Force

    } #process

    End {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #end

} #close Restore-RecyleBinItem

现在恢复已删除的项目非常简单。

[玩转系统] 使用 PowerShell 管理回收站

我可能应该修改恢复功能以让我指定备用位置。或者添加一些逻辑以不覆盖现有文件。但我可以将这些脚本挑战留给您。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯