I have a script that for a given folder looks for all the subfolders recursively and in each subfolder does something to XML files that are inside.
foreach ($folderItem in ($folderItems = Get-ChildItem -Path $initialPath -Recurse -Directory)) {
Write-Host("Doing something with $folderItem")
}
Just now I got a call from a user saying it doesn't work. So, instead of the folder, containing subfolders with XML files, she was feeding one of the subfolders (apparently she wanted only that subfolder's XML files processed). Naturally, that subfolder didn't have any other subfolders in it so
$folderItems = Get-ChildItem -Path $initialPath -Recurse -Directory
was empty.
Now, I'm thinking - how can I get an object of type DirectoryInfo (that's what Get-ChildItem
returns) and manually add a folder to it - so when iterating through it, it would include that folder as well (in my case folder with $initialPath
as path)? I can't just attach folder object to it:
Method invocation failed because [System.IO.DirectoryInfo] does not contain a method named 'op_Addition'.
One of the ways - maybe get parent folder for my folder, and then run Get-ChildItem
on it - but how to filter out any siblings to my folder?
Ok, so me and @Santiago in comments came to the same solution essentially.
$folderItems = @(Get-Item -Path $initialPath; Get-ChildItem -Path $initialPath -Recurse -Directory)
foreach ($folderItem in $folderItems) {
Write-Host("Doing something with $folderItem")
}
$folderItem
in this case is an array, but looks like I can iterate through each item in array correctly still (meaning that it iterates through each folder object). And $folderItems.Count
gives not the number of objects in the array (2) but total number of folders.
I need that since I output progress of the task.
Awesome!