ファイルまたはフォルダを指定してごみ箱に移動するサンプルスクリプトを公開します。
エラー処理等が不足していますが、参考にしてください。
以下に使用例などを記します。
使用上の注意
USBメモリなど外部にあるファイルはごみ箱に移動できません。
これはエクスプローラー操作による動作と同様です。
当サイトの資料により直接的および間接的障害が生じても一切責任を負いません。
あらかじめご了承ください。自己責任のもとで本資料をご利用ください。
PS C:\> [System.Environment]::OSVersion | Format-List
Platform : Win32NT
ServicePack :
Version : 10.0.17134.0
VersionString : Microsoft Windows NT 10.0.17134.0
PS C:\> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.17134.228
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.228
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
以下のサンプルスクリプトは2つのファンクションを記述してあります。
ToRecycle.zip : (SJIS, CRLF)
Add-Type -AssemblyName Microsoft.VisualBasic
# フォルダをゴミ箱に移動する
function Folder-ToRecycleBin($target_dir_path) {
if ((Test-Path $target_dir_path) -And ((Test-Path -PathType Container (Get-Item $target_dir_path)))) {
$fullpath = (Get-Item $target_dir_path).FullName
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
} else {
Write-Output "'$target_dir_path' is not directory or not found."
}
}
# ファイルをゴミ箱に移動する
function File-ToRecycleBin($target_file_path) {
if ((Test-Path $target_file_path) -And ((Test-Path -PathType Leaf (Get-Item $target_file_path)))) {
$fullpath = (Get-Item $target_file_path).FullName
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
} else {
Write-Output "'$target_file_path' is not file or not found."
}
}
以下、実際に上記スクリプトを使用してみます。
PS C:\work> (Get-Location).Path
C:\work
PS C:\work> Get-ChildItem *
PS C:\work> "Hello" | Out-File hello.txt -Encoding default
PS C:\work> New-Item folder -Type Directory
ディレクトリ: C:\work
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2018/09/09 15:17 folder
PS C:\work> Get-ChildItem
ディレクトリ: C:\work
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2018/09/09 15:17 folder
-a---- 2018/09/09 15:17 7 hello.txt
File-ToRecycleBin .\hello.txt
Folder-ToRecycleBin .\folder\
以上のように、ファイルおよびフォルダがごみ箱に移動されています。
再度注意!
USBメモリなどの外部ストレージの場合、移動されずに削除されます。
これは、エクスプローラーでの操作と同じになりますのご注意ください。
上記の2つのファンクションをAliasとして設定すれば、便利に使えるかもしれません。
Set-Aliasで本ファンクションを設定しています。
Remove-Item Alias:del Set-Alias -name del -value File-ToRecycleBin
Remove-Item Alias:rmdir Set-Alias -name rmdir -value Folder-ToRecycleBin 上記のエイリアス設定により、del, rmdirでファイルを指定すると、ごみ箱に移動されます。
以上、PowerShellでファイルおよびフォルダをゴミ箱に移動するサンプルスクリプトでした。