简体   繁体   English

如何使用 PowerShell 2.0 递归删除整个目录?

[英]How to recursively delete an entire directory with PowerShell 2.0?

What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell?在 PowerShell 中强制删除目录及其所有子目录的最简单方法是什么? I am using PowerShell V2 in Windows 7.我在 Windows 7 中使用 PowerShell V2。

I have learned from several sources that the most obvious command, Remove-Item $targetDir -Recurse -Force , does not work correctly.我从多个来源了解到,最明显的命令Remove-Item $targetDir -Recurse -Force无法正常工作。 This includes a statement in the PowerShell V2 online help (found using Get-Help Remove-Item -Examples ) that states:这包括 PowerShell V2 在线帮助(使用Get-Help Remove-Item -Examples )中的声明:

...Because the Recurse parameter in this cmdlet is faulty, the command uses the Get-Childitem cmdlet to get the desired files, and it uses the pipeline operator to pass them to the Remove-Item cmdlet... ...因为此 cmdlet 中的 Recurse 参数有问题,该命令使用 Get-Childitem cmdlet 获取所需文件,并使用管道运算符将它们传递给 Remove-Item cmdlet ...

I have seen various examples that use Get-ChildItem and pipe it to Remove-Item , but the examples usually remove some set of files based on a filter, not the entire directory.我见过使用Get-ChildItem并将其通过管道传递给Remove-Item 的各种示例,但这些示例通常基于过滤器删除一些文件集,而不是整个目录。

I am looking for the cleanest way to blow out an entire directory, files and child directories, without generating any user warning messages using the least amount of code.我正在寻找最干净的方法来清除整个目录、文件和子目录,而不会使用最少的代码生成任何用户警告消息。 A one-liner would be nice if it is easy to understand.如果易于理解,单线会很好。

Remove-Item -Recurse -Force some_dir

does indeed work as advertised here.确实像这里宣传的那样工作。

rm -r -fo some_dir

are shorthand aliases that work too.是也有效的速记别名。

As far as I understood it, the -Recurse parameter just doesn't work correctly when you try deleting a filtered set of files recursively.据我了解,当您尝试递归删除一组过滤的文件时, -Recurse参数无法正常工作。 For killing a single dir and everything below it seems to work fine.对于杀死单个目录及其下面的所有内容似乎都可以正常工作。

I used:我用了:

rm -r folderToDelete

This works for me like a charm (I stole it from Ubuntu).这对我来说就像一个魅力(我从 Ubuntu 偷了它)。

When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.使用简单的Remove-Item "folder" -Recurse递归删除文件时,我有时会看到间歇性错误: [folder] cannot be removed because it is not empty.

This answer attempts to prevent that error by individually deleting the files.此答案试图通过单独删除文件来防止该错误。

function Get-Tree($Path,$Include='*') { 
    @(Get-Item $Path -Include $Include -Force) + 
        (Get-ChildItem $Path -Recurse -Include $Include -Force) | 
        sort pspath -Descending -unique
} 

function Remove-Tree($Path,$Include='*') { 
    Get-Tree $Path $Include | Remove-Item -force -recurse
} 

Remove-Tree some_dir

An important detail is the sorting of all the items with pspath -Descending so that the leaves are deleted before the roots.一个重要的细节是使用pspath -Descending对所有项目进行排序,以便在根之前删除叶子。 The sorting is done on the pspath parameter since that has more chance of working for providers other than the file system.排序是在pspath参数上完成的,因为它有更多的机会为文件系统以外的提供者工作。 The -Include parameter is just a convenience if you want to filter the items to delete.如果要过滤要删除的项目, -Include参数只是一种方便。

It's split into two functions since I find it useful to see what I'm about to delete by running它分为两个功能,因为我发现通过运行查看我将要删除的内容很有用

Get-Tree some_dir | select fullname
rm -r ./folder -Force    

...为我工作

Try this example.试试这个例子。 If the directory does not exist, no error is raised.如果目录不存在,则不会引发错误。 You may need PowerShell v3.0.您可能需要 PowerShell v3.0。

remove-item -path "c:\Test Temp\Test Folder" -Force -Recurse -ErrorAction SilentlyContinue

使用老式的 DOS 命令:

rd /s <dir>

For some reason John Rees' answer sometimes did not work in my case.出于某种原因,约翰·里斯的回答有时在我的情况下不起作用。 But it led me in the following direction.但它使我朝着以下方向前进。 First I try to delete the directory recursively with the buggy -recurse option.首先,我尝试使用 buggy -recurse 选项递归删除目录。 Afterwards I descend into every subdir that's left and delete all files.之后,我进入剩下的每个子目录并删除所有文件。

function Remove-Tree($Path)
{ 
    Remove-Item $Path -force -Recurse -ErrorAction silentlycontinue

    if (Test-Path "$Path\" -ErrorAction silentlycontinue)
    {
        $folders = Get-ChildItem -Path $Path –Directory -Force
        ForEach ($folder in $folders)
        {
            Remove-Tree $folder.FullName
        }

        $files = Get-ChildItem -Path $Path -File -Force

        ForEach ($file in $files)
        {
            Remove-Item $file.FullName -force
        }

        if (Test-Path "$Path\" -ErrorAction silentlycontinue)
        {
            Remove-Item $Path -force
        }
    }
}

To avoid the "The directory is not empty" errors of the accepted answer, simply use the good old DOS command as suggested before.为避免已接受答案的“目录不为空”错误,只需按照之前的建议使用旧的 DOS 命令。 The full PS syntax ready for copy-pasting is:准备复制粘贴的完整 PS 语法是:

& cmd.exe /c rd /S /Q $folderToDelete

Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors.删除整个文件夹树有时会起作用,有时会因“目录非空”错误而失败。 Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors.随后尝试检查文件夹是否仍然存在可能会导致“拒绝访问”或“未经授权的访问”错误。 I do not know why this happens, though some insight may be gained from this StackOverflow posting .我不知道为什么会发生这种情况,尽管可以从这篇 StackOverflow 帖子中获得一些见解。

I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays.通过指定文件夹中项目的删除顺序和添加延迟,我已经能够解决这些问题。 The following runs well for me:以下对我来说运行良好:

# First remove any files in the folder tree
Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force

# Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }

# Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
Remove-Item -LiteralPath $FolderToDelete -Recurse -Force

# Finally, give Windows some time to finish deleting the folder (try not to hurl)
Start-Sleep -Seconds 4

A Microsoft TechNet article Using Calculated Properties in PowerShell was helpful to me in getting a list of sub-folders sorted by depth. Microsoft TechNet 文章在 PowerShell 中使用计算属性对我获取按深度排序的子文件夹列表很有帮助。

Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (ie using ping as shown below).RD /S /Q类似的可靠性问题可以通过在RD /S /Q之前运行DEL /F /S /Q并在必要时第二次运行RD来解决 - 理想情况下中间有暂停(即使用如图所示的ping以下)。

DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
RD /S /Q "C:\Some\Folder\to\Delete" > nul
if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul
del <dir> -Recurse -Force # I prefer this, short & sweet

OR或者

remove-item <dir> -Recurse -Force

If you have a huge directory then what I usually do is如果你有一个巨大的目录,那么我通常做的是

while (dir | where name -match <dir>) {write-host deleting; sleep -s 3}

Run this on another powershell terminal and it will stop when it is done.在另一个 powershell 终端上运行它,它会在完成后停止。

If you're committed to powershell, you can use this, as explained in the accepted answer:如果您致力于使用 powershell,则可以使用它,如已接受的答案中所述:

rm -r -fo targetDir

But I've found it to be faster to use Windows Command Prompt但我发现使用 Windows 命令提示符更快

rmdir /s/q targetDir

In addition to being faster, another advantage to using the command prompt option is that it starts deleting files immediately (powershell does some enumeration first), so if something breaks while it's running, you've at least made some progress in deleting files.除了速度更快之外,使用命令提示符选项的另一个优点是它会立即开始删除文件(powershell 首先进行一些枚举),因此如果在运行时出现问题,您至少在删除文件方面取得了一些进展。

Another useful trick:另一个有用的技巧:

If you find a lot of files with same or similar name convention (like mac file with dot prefix name... that famous file pulltion), you can easily remove them with one single line from the powershell like this:如果您发现许多具有相同或相似名称约定的文件(例如带有点前缀名称的 mac 文件...那个著名的文件提取),您可以像这样从 powershell 中使用一行轻松删除它们:

ls -r .* | rm

This line is going to remove all files with a dot in the begining of the name inside the current directory, and all files with same circumstances inside other folders inside this directory too.此行将删除当前目录中名称开头带点的所有文件,以及该目录中其他文件夹中所有情况相同的文件。 Be aware about it when using it.使用时请注意这一点。 :D :D

I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point.我采取了另一种受上述@john-rees 启发的方法 - 特别是当他的方法在某些时候开始对我失败时。 Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest基本上递归子树并按路径长度对文件进行排序 - 从最长到最短删除

Get-ChildItem $tfsLocalPath -Recurse |  #Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  #Calculate the length of their path
    Sort-Object PathLength -Descending | #sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } | 
    Remove-Item -Force

Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808关于 -LiteralPath 魔法,这里有另一个可能会打击你的陷阱: https ://superuser.com/q/212808

真的很简单:

remove-item -path <type in file or directory name>, press Enter

To delete the complete contents including the folder structure use要删除包括文件夹结构在内的完整内容,请使用

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

The -recurse added to remove-item ensures interactive prompts are disabled.添加到remove-item-recurse确保禁用交互式提示。

There seems to be issues where Remove-Item -Force -Recurse can intermittently fail on Windows because the underlying filesystem is asynchronous.由于底层文件系统是异步的,似乎存在Remove-Item -Force -Recurse在 Windows 上间歇性失败的问题。 This answer seems to address it.这个答案似乎解决了这个问题。 The user has also been actively involved with the Powershell team on GitHub .该用户还积极参与了GitHub 上的 Powershell 团队。

Based on @John Rees 's answer with some improvements.基于@John Rees回答并进行了一些改进。

Initial files tree .初始文件树。 /f /F

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
│   X-Update-PowerShellCoreFxs.ps1
│   z
│   Z-Config.json
│   Z-CoreFxs.ps1
│
├───HappyBirthday Unicorn
│       collection-of-unicorns-and-hearts-with-rainbows.zip
│       hand-drawing-rainbow-design.zip
│       hand-drawn-unicorn-birthday-invitation-template (2).zip
│       hontana.zip
│       Unicorn - Original.pdf
│       Unicorn-free-printable-cake-toppers.png
│       Unicorn.pdf
│       Unicorn.png
│       Unicorn2.pdf
│       Unicorn3.pdf
│       Unicorn4.pdf
│       Unicorn5.pdf
│       UnicornMLP.pdf
│
├───x
└───y

Code代码

function Get-ItemTree() {
    param (
        [Parameter()]
        [System.String]
        $Path = ".",

        [Parameter()]
        [System.String]
        $Include = "*",

        [Parameter()]
        [switch]
        $IncludePath,

        [Parameter()]
        [switch]
        $Force

    )
    $result = @()
    if (!(Test-Path $Path)) {
        throw "Invalid path. The path `"$Path`" doesn't exist." #Test if path is valid.
    }
    if (Test-Path $Path -PathType Container)
    {
        $result += (Get-ChildItem "$Path" -Include "$Include" -Force:$Force -Recurse) # Add all items inside of a container, if path is a container.
    }
    if($IncludePath.IsPresent)
    {
        $result += @(Get-Item $Path -Force) # Add the $Path in the result.
    }
    $result = ,@($result | Sort-Object -Descending -Unique -Property "PSPath") # Sort elements by PSPath property, order in descending, remove duplicates with unique.
    return  $result
}

function Remove-ItemTree {
    param (
        [Parameter()]
        [System.String]
        $Path, 

        [Parameter()]
        [switch]
        $ForceDebug
    )
    (Get-ItemTree -Path $Path -Force -IncludePath) | ForEach-Object{
        Remove-Item "$($_.PSPath)" -Force
        if($PSBoundParameters.Debug.IsPresent)
        {
            Write-Debug -Message "Deleted: $($_.PSPath)" -Debug:$ForceDebug
        }
    }
}

Write-Host "███ Test 1"
$a = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$true # Tree of a file path. 1 element the file (IncludePath parameter = $true)
$a | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 2"
$b = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$false # Tree of a file path. No Result (IncludePath parameter = $false)
$b | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 3"
$c = Get-ItemTree "." -Force -Include "*" -IncludePath:$true # Tree of a container path. All elements of tree and the container included (IncludePath parameter = $true).
$c | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 4"
$d = Get-ItemTree "." -Force -Include "*" -IncludePath:$false # All elements of tree, except the container (IncludePath parameter = $false).
$d | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Remove-ItemTree -Path "./HappyBirthday Unicorn" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./x" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./y" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./z" -Debug -ForceDebug #Remove file. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.

Get-ChildItem -Force

Output输出

███ Test 1
"Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json"

███ Test 2

███ Test 3
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",       
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",   
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",   
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx"
]

███ Test 4
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn"
]

DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\UnicornMLP.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn5.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn4.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn3.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn2.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn-free-printable-cake-toppers.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn - Original.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hontana.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawn-unicorn-birthday-invitation-template (2).zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawing-rainbow-design.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\collection-of-unicorns-and-hearts-with-rainbows.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\x
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\y
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\z


    Directory: C:\Users\Megam\OneDrive\Escritorio\pwshcfx

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---           17/5/2021     1:57            272 X-Update-PowerShellCoreFxs.ps1
la---           14/5/2021    18:51            252 Z-Config.json
la---           17/5/2021     4:04          30931 Z-CoreFxs.ps1

tree .树 。 /f /F

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
    X-Update-PowerShellCoreFxs.ps1
    Z-Config.json
    Z-CoreFxs.ps1

No subfolders exist

while rm -r yields good results, the following method is faster:虽然 rm -r 产生良好的结果,但以下方法更快:

$fso = New-Object -ComObject scripting.filesystemobject
$fso.DeleteFolder("D:\folder_to_remove")

To test this you can easily create a folder with X files (I used:Disk Tools to quickly generate the files).为了测试这一点,您可以轻松地创建一个包含 X 文件的文件夹(我使用:磁盘工具来快速生成文件)。

And then run each of the variants using:然后使用以下命令运行每个变体:

Measure-Command {rm D:\FOLDER_TO_DELETE -r}
Measure-Command {Remove-Item -Path D:\FOLDER_TO_DELETE -Recurse -Force}
Measure-Command {rd -r FOLDER_TO_DELETE }
$fso.DeleteFolder("D:\folder_to_remove")
Measure-Command {$fso.DeleteFolder("D:\FOLDER_TO_DELETE")}

the results on my test folder were:我的测试文件夹上的结果是:

Remove-Item - TotalMilliseconds : 1438.708
rm - TotalMilliseconds : 1268.8473
rd - TotalMilliseconds : 739.5385
FSO - TotalMilliseconds : 676.8091

The results vary but on my system the winner was the fileSystemObject.结果各不相同,但在我的系统上,获胜者是 fileSystemObject。 I recommend testing this on the target file system to see which method is the best for you.我建议在目标文件系统上测试这个,看看哪种方法最适合你。

Add a custom function in your PowerShell $profile :在 PowerShell $profile添加自定义函数:

function rmrf([string]$Path) {
    try {
        Remove-Item -Recurse -ErrorAction:Stop $Path
    } catch [System.Management.Automation.ItemNotFoundException] {
        # Ignore
        $Error.Clear()
    }
}

This is the most accurate representation of rm -rf behavior.这是rm -rf行为的最准确表示。

$users = get-childitem \\ServerName\c$\users\ | select -ExpandProperty name

foreach ($user in $users)

{
remove-item -path "\\Servername\c$\Users\$user\AppData\Local\Microsoft\Office365\PowerShell\*" -Force -Recurse
Write-Warning "$user Cleaned"
}

Wrote the above to clean some logfiles without deleting the parent directory and this works perfectly!写上面的内容是为了在不删除父目录的情况下清理一些日志文件,这非常有效!

rm -r <folder_name>
c:\>rm -r "my photos"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM