user3671361
user3671361

Reputation: 175

Powershell for loop

I have to print all the directories and all the files. But If I find a directory I have to "enter to the directory" and print the files stored in that directory. It only have two levels, the first level is full fo directorys and the second level there are files.

I've tried this but, it doesn't enter to the directory, it all the directorys two times

$correcte = $args.Count
if ($correcte -lt 1){
    forEach ($item in (Get-ChildItem)){ //first level of directories
       if($item.PSIsContainer){
          forEach ($item in (Get-ChildItem)){               
             write-host $item //this should print the file inside the directory
          }
        }
    }
}
else{
    write-host "You don't have to pass any parameter"
}

Upvotes: 0

Views: 255

Answers (3)

Paul
Paul

Reputation: 5871

Get-Childitem has a -recurse parameter that does exactly that. If you only want to print out the item like it was generated by gci the following will suffice:

Get-Childitem -recurse

Upvotes: 0

arco444
arco444

Reputation: 22871

You need to re-use the $item variable in the second loop once you've determined it's a directory.

As Enrico points out, also best to use a different variable name:

$correcte = $args.Count
if ($correcte -lt 1){
    forEach ($item in (Get-ChildItem)){ //first level of directories
       if($item.PSIsContainer){
          forEach ($subitem in (Get-ChildItem $item)){               
             write-host $subitem.FullPath //this should print the file inside the directory
          }
        }
    }
}
else{
    write-host "You don't have to pass any parameter"
}

Depending on your powershell version, you might be able to simplify this by just getting the directories in the first place:

Get-ChildItem -Directory | % { gci $_ } 

Upvotes: 3

Enrico
Enrico

Reputation: 10685

It looks like Get-ChildItem is executed in the same folder both times. You need to "move" into the target directory before calling Get-ChildItem again.

As a side note, it's not a great idea to reuse the variable name item again in your inner loop. It's confusing.

Upvotes: 0

Related Questions