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

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;

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

發佈留言