Script-subfolders

This topic contains 6 replies, has 2 voices, and was last updated by Profile photo of Matic Matic 1 week, 1 day ago.

  • Author
    Posts
  • #58870
    Profile photo of Matic
    Matic
    Participant

    Hello, i'm completely new to powershell.
    I'm trying to make a script where user enter path of a folder (C:\xx). The script in this folder and all subfolders (recursively) must find all files older than x days (x entered by the user). For each file that's found the script asks user if it wants to be deleted. If user enter "yes", script actually delete a file.
    My problem is that when script asks me if i want to delete file in subfolder (C:\xx\bin) and i enter yes i get error message : Remove-Item : Cannot find path 'C:\xx\bin\demo32.exe because it does not exist. (but it's actually there). I have this problem only in subfolders..

    ps. Sorry for my english

    $a = Read-Host "Path of a Folder: "
    $b = Read-Host "Enter x number: "
    $c = Get-ChildItem -Path $a -Include *.* -Recurse  |  Where-Object {$_.LastWriteTime -lt(Get-Date).AddDays(-$b)}
    
    foreach ($item in $c) {
    	$decision = Read-Host "Do you want to delete $item ? (yes/no)"
    	if($decision -eq "yes")
    {
    	Remove-Item -Path $a\$item -Force
    }
    }
    
  • #58875
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant

    As you can see when your script asks for confirmation, $Item already has the path information. You don't need to add $a.
    Instead of

    Remove-Item -Path $a\$item -Force

    it should be enough to do

    Remove-Item -Path $item -Force
    • #58879
      Profile photo of Matic
      Matic
      Participant

      I tried, but it's still not working.

    • #58884
      Profile photo of Olaf Soyk
      Olaf Soyk
      Participant

      Do you get errors?

    • #58887
      Profile photo of Matic
      Matic
      Participant

      Yes:

      Remove-Item : Cannot find path 'C:\xx\C:\xx\Bin\demo32.exe' because it does not exist. // why is here 2x c:\...?
      + Remove-Item $a\$item -Force
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : ObjectNotFound: (C:\xx...\Bin\demo32.exe:String) [Remove-Item], ItemNotFoundException
      + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

    • #58888
      Profile photo of Olaf Soyk
      Olaf Soyk
      Participant

      So you did not change your code, right? It will not work this way. You will have to remove the '$a\' from your 'Remove-Item'!

      The error message even shows it to you.

    • #58893
      Profile photo of Matic
      Matic
      Participant

      It's working :). I forgot to delete '$a'. Thank you for your help

You must be logged in to reply to this topic.