Search code examples
powershelltestingpathscriptingpester

"Path cannot be found" Pester Test Results


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.


Solution

  • 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.