0

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"
}

3 Answers 3

3

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 $_ } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.