копирование файлов из корзины - PullRequest
0 голосов
/ 08 июля 2019

Здесь ( Список файлов в корзине ) Я нашел сообщение @ Smile4ever, в котором говорится, как получить исходное местоположение для файлов в корзине:

(New-Object -ComObject Shell.Application).NameSpace(0x0a).Items()
|select @{n="OriginalLocation";e={$_.ExtendedProperty("{9B174B33-40FF-11D2-A27E-00C04FC30871} 2")}},Name
| export-csv -delimiter "\" -path C:\Users\UserName\Desktop\recycleBinFiles.txt -NoTypeInformation

(gc C:\Users\UserName\Desktop\recycleBinFiles.txt | select -Skip 1)
| % {$_.Replace('"','')}
| set-content C:\Users\UserName\Desktop\recycleBinFiles.txt

I 'Я хотел бы скопировать их куда-нибудь (на случай, если мне сказали, что некоторые из них не должны быть удалены, а кто-то опустошил корзину).

Здесь (https://superuser.com/questions/715673/batch-script-move-files-from-windows-recycle-bin) Я нашел @gm2 пост для их копирования

$shell = New-Object -ComObject Shell.Application  
$recycleBin = $shell.Namespace(0xA) #Recycle Bin  
$recycleBin.Items() | %{Copy-Item $_.Path ("C:\Temp\{0}" -f $_.Name)}   

И они работают нормально, но мне нужно что-то большее.

Я ничего не знаю о powershell, но что я хотел бы сделатьбыло бы: для каждого файла в Корзине создать свою исходную папку расположения в папке резервной копии C: \ Temp и скопировать туда файл (поэтому у меня не будет проблемы с несколькими файлами с тем же именем).

А затем сжать этот C: \ Temp.

Есть ли способ сделать это? Спасибо!

1 Ответ

1 голос
/ 08 июля 2019

Вы должны быть в состоянии сделать это так:

# Set a folder path INSIDE the C:\Temp folder to collect the files and folders
$outputPath = 'C:\Temp\RecycleBackup'
# afterwards, a zip file is created in 'C:\Temp' with filename 'RecycleBackup.zip'

$shell = New-Object -ComObject Shell.Application  
$recycleBin = $shell.Namespace(0xA)
$recycleBin.Items() | ForEach-Object {
    # see https://docs.microsoft.com/en-us/windows/win32/shell/shellfolderitem-extendedproperty
    $originalPath = $_.ExtendedProperty("{9B174B33-40FF-11D2-A27E-00C04FC30871} 2")
    # get the root disk from that original path
    $originalRoot = [System.IO.Path]::GetPathRoot($originalPath)

    # remove the root from the OriginalPath
    $newPath = $originalPath.Substring($originalRoot.Length)

    # change/remove the : and \ characters in the root for output
    if ($originalRoot -like '?:\*') {  
        # a local path.  X:\ --> X
        $newRoot = $originalRoot.Substring(0,1)
    }
    else {                             
        # UNC path.  \\server\share --> server_share
        $newRoot = $originalRoot.Trim("\") -replace '\\', '_'   
        #"\"# you can remove this dummy comment to restore syntax highlighting in SO
    }

    $newPath = Join-Path -Path $outputPath -ChildPath "$newRoot\$newPath"
    # if this new path does not exist yet, create it
    if (!(Test-Path -Path $newPath -PathType Container)) {
        New-Item -Path $newPath -ItemType Directory | Out-Null
    }

    # copy the file or folder with its original name to the new output path
    Copy-Item -Path $_.Path -Destination (Join-Path -Path $newPath -ChildPath $_.Name) -Force -Recurse
}

# clean up the Com object when done
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
$shell = $null

Для следующего кода требуется PowerShell версии 5

# finally, create a zip file of this RecycleBackup folder and everything in it.
# append a '\*' to the $outputPath variable to enable recursing the folder
$zipPath = Join-Path -Path $outputPath -ChildPath '*'
$zipFile = '{0}.zip' -f $outputPath.TrimEnd("\")
#"\"# you can remove this dummy comment to restore syntax highlighting in SO

# remove the zip file if it already exists
if(Test-Path $zipFile -PathType Leaf) { Remove-item $zipFile -Force }
Compress-Archive -Path $zipPath -CompressionLevel Optimal -DestinationPath $zipFile -Force

Чтобы создать zip-файл в PowerShell ниже версии 5

Если у вас нет PowerShell 5 или более поздней версии, Compress-Archive недоступен.
Чтобы создать zip-файл из C:\Temp\RecycleBackup, вы можете сделать это вместо:

$zipFile = '{0}.zip' -f $outputPath.TrimEnd("\")
#"\"# you can remove this dummy comment to restore syntax highlighting in SO

# remove the zip file if it already exists
if(Test-Path $zipFile -PathType Leaf) { Remove-item $zipFile -Force }
Add-Type -AssemblyName 'System.IO.Compression.FileSystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($outputPath, $zipFile) 

Конечно, для этого вы также можете использовать стороннее программное обеспечение, такое как 7Zip. В сети есть множество примеров, как использовать это в Powershell, например, здесь

В соответствии с вашим последним запросом на удаление папки 'RecycleBackup' после создания архива

Remove-Item -Path $outputPath -Recurse -Force

Надеюсь, это поможет

...