1

Im testing out a script on Pester. I keep getting a Path cannot be found error. Apparently something is wrong with some of my lines.

$userFolders = Get-ChildItem C:\Users -Directory
foreach($folder in $userFolders)
{
    Get-ChildItem C:\Users\$folder\AppData\Local\Temp -Recurse | Remove-Item -Recurse -Force
    Get-ChildItem C:\Users\$folder\AppData\Local\Google\Chrome\User Data\Default\Cache -Recurse | Remove-Item -Recurse -Force 
}
Get-ChildItem C:\Windows\Temp -Recurse | Remove-Item -Recurse -Force

I can't seem to find what is wrong, but I know it is somewhere here. Any help would be greatly appreciated.

techguy1029
  • 743
  • 10
  • 29

4 Answers4

2

$folder is an object. Casting to string will give you the folder name. You can do this by using quotes.

As Mark has identified, you would also need quotes if there a space in the path.

$userFolders = Get-ChildItem C:\Users -Directory

foreach($folder in $userFolders) {

    Write-Host "This is the folder object:"
    $folder

    Write-Host "This is folder object cast to string: $folder"

    Get-ChildItem "C:\Users\$folder\AppData\Local\Temp" -Recurse | Remove-Item -Recurse -Force        
    Get-ChildItem "C:\Users\$folder\AppData\Local\Google\Chrome\User Data\Default\Cache" -Recurse | Remove-Item -Recurse -Force
}

Get-ChildItem C:\Windows\Temp -Recurse | Remove-Item -Recurse -Force
G42
  • 9,791
  • 2
  • 19
  • 34
1

One of your paths has a space in it so needs to wrapped in quotes:

Get-ChildItem "C:\Users\$folder\AppData\Local\Google\Chrome\User Data\Default\Cache" -Recurse | Remove-Item -Recurse -Force

It needs to be double quotes so that the $folder variable is still expanded.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
0

Probably not every user folder has a 'Google' sub-directory

C:\Users\$folder\AppData\Local\**Google**\...
Nas
  • 1,243
  • 6
  • 7
0

The other answers have pointed out the main flaw in your script which is the lack of quotes. There is also some redundancy in two ways.

  • Repetition of Get-ChildItem <something> | Remove-Item <something>
  • Recursion on both sides of the pipe.

Consider the following:

function Get-TempFolderItem {
  foreach ($Local in (Get-ChildItem -Path "C:\Users\*\AppData\Local")) {
    'Temp','Google\Chrome\User Data\Default\Cache' |
    ForEach-Object { Get-ChildItem -Path "$Local\$_" -Recurse }
  }
}
Get-TempFolderItem | Remove-Item -Force

Here there is less repetition which simplifies debugging if you make a mistake. And if the getting of directory content is exhaustive, the removal shouldn't have to be.

Because you are saying that this is in the context of testing you should probably look into mocking for something like removal of files. With temp-files it doesn't matter much if you delete something you didn't intend to, but generally that is something you need to avoid when testing.

You can do this by writing

 Mock Remove-Item {}

inside the Describe block.

Hope this answer is useful to you.

dizzi90
  • 80
  • 8