I have a powershell script, which is supposed to navigate folders and subfolders of a specified directory. Once at the lowest level (when there are no more sub-folders, but only files), it will process the files. For my example, let's assume I have the following folders and files:
c:\temp\filder1\file1.txt
c:\temp\filder2\file2.txt
c:\temp\filder3\file3.txt
The problem happens when I am trying to go from the lowest-level folder to processing files in that folder: $files = Get-ChildItem $folder. It seems that somehow the object folder is converted into just a string with the folder's name. I get the error, which is now using my user's default path with the folder name appended, which, of course, fails, because now such folder exists in my default path. The error is something like:
Get-ChildItem : Cannot find path 'C:\Users\my.name\Documents\Powershell\Powershell_Scripts\folder1' because it does not exist.
The path I would expect is 'c:\temp\folder1'
Here the simplified version of my script:
Param(
[Parameter(Position = 1)] [string] $source_share_full_path = "c:\temp\" # path to a top-level share
)
$folders = Get-ChildItem $source_share_full_path
#Loop through all the folders
ProcessAllSubfolders($folders)
function ProcessAllSubfolders($folderCollection) {
foreach ($folder in $folderCollection)
{
if ($folder.Subfolders.Count -gt 0)
{
ProcessAllSubfolders($folder.SubFolders)
}
else
{
Write-Output "`nReady to process files in a folder : $folder.FullName `n "
$files = Get-ChildItem $folder.FullName
ProcessFiles($files)
}
}
}
function ProcessFiles($files) {
foreach ($file in $files)
{
Write-Output "`nReady to process file: $file `n "
}
}
The credit for the method of navigating sub-folders belongs here
I appreciate any pointers!
Get-ChildItemreturns aDirectoryInfotype for a folder, and they don't have a property.Subfolders(unless that's new in PowerShell 5?), so the count will never be greater than 0. From that, I guess you're testing only the simplest case with one level of folder under c:\temp? Also because you're calling the functions before you define them, I imagine you're actually running the function body from the previous run of the script, where you typed$folder.Name, then corrected it? I can't see another great possibility - TessellatingHeckler