powershell脚本删除无效的快捷方式和空文件夹 2


运行脚本如果不指定路径参数, 默认删除开始菜单的无效快捷方式和空文件夹, 删除空文件夹会有确认提示

 param
(
    [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
    [String]$dir
) 
function Remove-InvalidShortcut () {
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [String]$dir
    ) 
    $WshShell = New-Object -comObject WScript.Shell
    $StartScreenLocation = $dir
    $AllLnkFiles = Get-ChildItem -Path $StartScreenLocation -Filter *.lnk -recurse
    Foreach ($LnkFile in $AllLnkFiles) {
        $LnkFilePath = $LnkFile.FullName
        $LnkShortcut = $WshShell.CreateShortcut($LnkFilePath)
        $LnkTargetPath = $LnkShortcut.TargetPath
    
        if (!([String]::IsNullOrEmpty($LnkTargetPath))) {
            If (!(Test-Path -Path $LnkTargetPath)) {
                Remove-Item -Path $LnkFilePath
                Write-Host "The ""$($LnkFile.BaseName)"" shortcut file was successfully removed." -ForegroundColor Green
            }
        }
    }
    
    Get-ChildItem -Path $dir -recurse | Where-Object { $_.PSIsContainer -and `
        @(Get-ChildItem -LiteralPath $_.Fullname -Recurse | Where-Object {!$_.PSIsContainer}).Length -eq 0} |
        Remove-Item -recurse -Confirm
}

if([String]::IsNullOrEmpty($dir)){
    Remove-InvalidShortcut "$env:APPDATA\Microsoft\Windows\Start Menu\Programs"
    Remove-InvalidShortcut "$env:ProgramData\Microsoft\Windows\Start Menu\Programs"
}else{
    Remove-InvalidShortcut $dir
}
本文链接: https://www.pstips.net/remove-useless-shortcut-and-folder.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

2 条评论 “powershell脚本删除无效的快捷方式和空文件夹