Author Posts

November 28, 2016 at 10:26 pm

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

November 28, 2016 at 11:49 pm

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

November 29, 2016 at 6:19 am

I tried, but it's still not working.

November 29, 2016 at 9:37 am

Do you get errors?

November 29, 2016 at 10:11 am

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

November 29, 2016 at 10:14 am

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.

November 29, 2016 at 10:22 am

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