PowerShell 移動檔案或資料夾到資源回收桶

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Add-Type -AssemblyName Microsoft.VisualBasic
function Remove-Item-ToRecycleBin($Path) {
    $item = Get-Item -Path $Path -ErrorAction SilentlyContinue
    if ($item -eq $null)
    {
        Write-Error("'{0}' not found" -f $Path)
    }
    else
    {
        $fullpath=$item.FullName
        Write-Verbose ("Moving '{0}' to the Recycle Bin" -f $fullpath)
        if (Test-Path -Path $fullpath -PathType Container)
        {
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
        else
        {
             [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
    }
}
 
Set-Alias rm Remove-Item-ToRecycleBin -Option AllScope
 
$Path = "D:\test"
rm $Path;

1
2
3
4
5
6
7
8
9
10
11
12
function Recycle-Item {
    param([string] $Path)
 
    $shell = New-Object -ComObject 'Shell.Application'
 
    $shell.NameSpace(0).
           ParseName($Path).
           InvokeVerb('Delete')
}
 
$Path = "D:\test"
Recycle-Item $Path

發佈留言