Get-ChildItem on a folder is going through the first folder 2 times

Hi, first post here to request some help.

I have a script, that opens a dialog to request a folder selection.

It saves it to a variable $root_folder, and the go into a foreach loop to iterate over the folders in that $root_folder.

It works, but it iterates two times over the first folder always. I’m pasting the simplified code below.

Thanks!

Function get-folder()

Function to open a dialog to select folder

{

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog

$foldername.Description = "Select a folder"

$foldername.rootfolder = "MyComputer"

if($foldername.ShowDialog() -eq "OK")

{

    $folder += $foldername.SelectedPath

}

return $folder
$root_folder = get-folder
foreach($folder in Get-ChildItem $root_folder -Directory){
# code that do something

}

 

 

I’m pretty unsure how your code snippets belong together / interact with each other. You do not show us the relevant code. Where do you define $root_folder?

Yes, sorry, I forgot to put that line, I just edited and now the variable gets the value from the function.

OK. But if I understand your code correctly the foreach loop is unnecessary. The function Get-Folder only provides a sinlge folder. So you’re iterating over 1 element. :wink:

The function gets the parent folder, and the foreach loops over all the subfolders.

The point is, it goes two times over the first subfolder.

I cannot reproduce your issue. You may remove all the current code you have at the moment in your loop and replace it with some test code. For example:

$root_folder = get-folder
foreach ($folder in Get-ChildItem $root_folder -Directory){
    $folder.Fullname
}

Thanks for the reply, that code in a folder with 2 subfolders give me 3 results:

  • full_path\subfolder1
  • full_path\subfolder1
  • full_path\subfolder2
 

That’s nearly impossible. You may restart your Powershell session with the option -noProfile. If that does not help try the code on another machine please.

Copied the content of the script on other file, same machine, same code, and it works.

Weird thing, thanks for the help.