programing

PowerShell 2.0에서 디렉토리 전체를 반복적으로 삭제하는 방법

instargram 2023. 4. 22. 08:27
반응형

PowerShell 2.0에서 디렉토리 전체를 반복적으로 삭제하는 방법

PowerShell에서 디렉토리와 모든 하위 디렉토리를 강제로 삭제하는 가장 간단한 방법은 무엇입니까?Windows 7에서 PowerShell V2를 사용하고 있습니다.

정보원으로부터 한 명령어인 '이러한 명령어를 .Remove-Item $targetDir -Recurse -Force가 올바르게 동작하지 않습니다.에는 PowerShell help에 (PowerShell V2 on-line help 사용).Get-Help Remove-Item -Examples는 다음과 같은 을 담고 있습니다.

...이 cmdlet의 Recurse 매개 변수가 고장났기 때문에 명령어는 Get-Childitem cmdlet을 사용하여 원하는 파일을 가져오고 파이프라인 연산자를 사용하여 해당 파일을 Remove-Item cmdlet으로 전달합니다...

Get-ChildItem을 사용하여 Remove-Item으로 파이핑하는 예는 여러 가지가 있습니다만, 일반적으로 디렉토리 전체가 아닌 필터에 근거해 파일 세트를 삭제합니다.

최소한의 코드를 사용하여 사용자 경고 메시지를 생성하지 않고 디렉토리, 파일 및 하위 디렉토리를 모두 삭제할 수 있는 가장 깨끗한 방법을 찾고 있습니다.알기 쉽다면 원라이너도 좋을 것 같아요.

Remove-Item -Recurse -Force some_dir

실제로 여기서 광고한 대로 작동합니다.

rm -r -fo some_dir

줄임말 가명도 통합니다.

론 가가 as as as as as as 。-Recurse필터링된 파일 세트를 반복적으로 삭제하려고 하면 파라미터가 올바르게 작동하지 않습니다.단 한 디르만 죽이면 그 아래 모든 게 잘 되는 것 같아.

사용:

rm -r folderToDelete

이것은 부적처럼 통한다(우분투에서 훔쳤다).

Simple을 하여 Remove-Item "folder" -Recurse에러가 발생하는 : 간헐 i : : : 。[folder] cannot be removed because it is not empty.

이 답변에서는 파일을 개별적으로 삭제하여 오류를 방지하려고 합니다.

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

은 모든 입니다.pspath -Descending잎이 뿌리보다 먼저 지워지도록 하는 거죠.는 렬음음 the the the the the로 한다.pspath파일 시스템 이외의 프로바이더에서 동작할 가능성이 높기 때문입니다.-Include삭제할 항목을 필터링하려면 매개 변수가 편리합니다.

이 기능은 두 가지 기능으로 나누어져 있습니다.실행함으로써 삭제하려는 내용을 확인할 수 있기 때문입니다.

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

...나에게 감사하다.

이 예를 사용해 보세요.디렉토리가 존재하지 않는 경우는, 에러는 발생하지 않습니다.PowerShell v3.0이 필요할 수 있습니다.

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

powershell에 전념하고 있는 경우는, 다음의 회답에 기재되어 있는 대로 사용할 수 있습니다.

rm -r -fo targetDir

하지만 Windows 명령 프롬프트를 사용하는 것이 더 빠릅니다.

rmdir /s/q targetDir

명령 프롬프트 옵션을 사용하면 속도가 빨라질 뿐만 아니라 파일 삭제가 즉시 시작되므로(powershell이 먼저 열거를 수행함), 실행 중에 문제가 발생할 경우 파일 삭제가 다소 개선됩니다.

old-stool DOS 명령어를 사용합니다.

rd /s <dir>

어떤 이유에서인지 John Rees의 답변은 때때로 내 경우에 효과가 없었다.하지만 그것은 나를 다음과 같은 방향으로 이끌었다.먼저 buggy - recurse 옵션을 사용하여 디렉토리를 재귀적으로 삭제하려고 합니다.그 후 남은 모든 서브디어로 이동하여 모든 파일을 삭제합니다.

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
        }
    }
}

승인된 답변의 "디렉토리가 비어 있지 않습니다" 오류를 방지하려면 앞서 제안한 대로 good old DOS 명령을 사용하십시오.복사 붙여넣기 가능한 PS 구문은 다음과 같습니다.

& cmd.exe /c rd /S /Q $folderToDelete
del <dir> -Recurse -Force # I prefer this, short & sweet

또는

remove-item <dir> -Recurse -Force

큰 디렉토리를 가지고 계신다면 제가 주로 하는 일은

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

다른 전원 셸 터미널에서 이 작업을 실행하면 작업이 완료되면 중지됩니다.

전체 폴더 트리를 삭제하면 "Directory not empty(디렉토리가 비어 있지 않음)" 오류로 인해 작업이 수행되거나 실패할 수 있습니다.이후에 폴더가 아직 존재하는지 확인하려고 하면 "접근 거부" 또는 "부정 액세스" 오류가 발생할 수 있습니다.Stack Overflow의 투고로부터 몇 가지 정보를 얻을 수 있습니다만, 왜 이러한 현상이 발생하는지는 알 수 없습니다.

폴더 내의 아이템이 삭제되는 순서를 지정하고 지연을 추가함으로써 이러한 문제를 해결할 수 있었습니다.다음과 같은 작업을 수행할 수 있습니다.

# 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

PowerShell에서 계산된 속성을 사용하는 Microsoft TechNet 기사는 하위 폴더 목록을 깊이별로 정렬하는 데 도움이 되었습니다.

RD / S / Q rd 、 RD / S / Q DEL / F / S / Q 를 실행하고, 필요에 따라서 RD 를 재실행하는 것으로, RD / S / Q 에서의 같은 신뢰성 문제를 해결할 수 있습니다(이상적으로는 다음과 같이 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

$profile:

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

입니다.rm -rf★★★★★★ 。

저는 위의 @john-rees에서 영감을 받은 다른 접근법을 취했습니다.특히 그의 접근방식이 어느 순간 나에게 실패하기 시작했을 때.기본적으로 하위 트리와 파일 경로 길이를 기준으로 파일을 정렬합니다. 가장 긴 파일부터 가장 짧은 파일까지 삭제합니다.

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

Literal Path 매직과 관련하여, https://superuser.com/q/212808에 또 다른 문제가 있을 수 있습니다.

문제가 있는 것 같습니다.Remove-Item -Force -Recurse기본 파일 시스템이 비동기이기 때문에 Windows에서 간헐적으로 장애가 발생할 수 있습니다. 답변이 그것을 해결하는 것 같다.사용자는 또한 GitHub의 Powershell 에 적극적으로 관여하고 있다.

rm - r은 양호한 결과를 얻을 수 있지만 다음 방법이 더 빠릅니다.

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

이를 테스트하려면 X 파일이 있는 폴더를 쉽게 만들 수 있습니다.디스크 툴을 사용하여 파일을 빠르게 생성할 수 있습니다).

그런 다음 다음을 사용하여 각 변형을 실행합니다.

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")}

테스트 폴더의 결과는 다음과 같습니다.

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

결과는 다양하지만 시스템에서는 fileSystemObject가 승리했습니다.대상 파일 시스템에서 테스트하여 어떤 방법이 가장 적합한지 확인하는 것이 좋습니다.

또 다른 유용한 요령:

이름 규칙이 같거나 유사한 파일이 많은 경우(도트 접두사 이름이 있는 mac 파일 등)그 유명한 파일 풀션)을 사용하면 다음과 같이 파워셸에서 한 줄로 쉽게 삭제할 수 있습니다.

ls -r .* | rm

이 행에서는, 현재의 디렉토리내의 이름의 선두에 점이 있는 모든 파일과 같은 상황을 가지는 이 디렉토리내의 다른 폴더내의 모든 파일이 삭제됩니다.사용 시 유의하시기 바랍니다. :D

폴더 구조를 포함한 전체 내용을 삭제하려면

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

-recurse에 추가된remove-item그럼 인터랙티브프롬프트가 디세블이 됩니다.

매우 심플:

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

@John Rees의 답변에 근거해, 몇개의 개선점이 있습니다.

초기 파일 트리 . /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

코드

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

산출량

███ 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

트리. /f

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

No subfolders exist
$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"
}

부모 디렉토리를 삭제하지 않고 몇 개의 로그 파일을 삭제하기 위해서, 상기의 내용을 기입했습니다.이 작업은 완벽하게 동작합니다.

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

언급URL : https://stackoverflow.com/questions/1752677/how-to-recursively-delete-an-entire-directory-with-powershell-2-0

반응형