Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

powershell - Cannot find path when using remove-item cmdlet

I wrote out a simple PowerShell script that backs up a directory to C: and then deletes any of the backup folders when its age = X days.

For some reason, when I use the Remove-Item cmdlet I'm getting a Remove-Item: Cannot find path 'C:Windowssystem32 [Sub-Folder name]' because it does not exist error.

Below is the snippet:

    $TargetFolder = "C:Folder"
    $Folders = get-childitem -path $TargetFolder
    foreach ($Folder in $Folders)
    {
      remove-item $Folder -recurse -force
    }

Within the $TargetFolder = "C:Folder", there are a few sub-folders. Examples: C:FolderSubfolderA, C:FolderSubfolderB, etc.

When I do a Write-Host for $Folder it lists SubFolderA, SubFolderB, etc, correctly so I'm not exactly sure why I'm getting a Cannot find path error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems that you want to do this on the basis of the directory LastWriteTime, but you did not mention -Directory on Get-ChildItem.

[cmdletbinding()]
Param()

$TargetFolder = "C:UserslitDocuments"
$Folders = Get-ChildItem -Path $TargetFolder -Directory
$Days = 80

foreach ($Folder in $Folders) {
    if ($Folder.LastWriteTime -lt (Get-Date).AddDays(-$Days)) {
        Write-Verbose "Deleting directory $($Folder.FullName)"
        Remove-Item -WhatIf "$($Folder.FullName)" -Recurse -Force
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...