0
votes

There have been a few discussions about the semantics of Get-ChildItem and I'm still having a hard time wrapping my head around a few scenarios.

Suppose I have the following file structure

C:\Test
│   TestFile1.txt
|   TestFile2.txt
│
├───SomeFolder
│   │   IgnoreFile1.txt
│   └───IgnoreFile2.txt
│   
└───OtherFolder

I want to run a command to select everything except OtherFolder and pipe it into another command. (For the sake of completeness, what I'm actually trying to do is to move everything into OtherFolder so the end result is other folder Contains both TestFile's and the SomeFolder with it's children)

No amount of fiddling with Get-ChildItem seems to give me the result that I want. As a simple example:

Get-ChildItem *.txt -Exclude TestFile1.txt 

returns the expected result. TestFile2.txt only.

Get-ChildItem *Folder

returns the two folders. However:

Get-ChildItem *Folder -Exclude OtherFolder

instead returns the children of SomeFolder. I don't really understand exactly what's going on. Why does adding -Exclude cause the folder contents to be returned. I've tried putting additional levels of files in the folder to test if it's recursive, but it only appears to go down one level.

How do I get a list of files and folders in a directory while excluding one (or more) directories?

2

2 Answers

2
votes

Maybe you should use Get-Item instead of ChildItem.
It seems to provide the data you expect.

PS C:\Users\v.......> Get-Item -Exclude Downloads Do*


    Verzeichnis: C:\Users\v.......


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d-r--        17.12.2014     17:07            Documents
d----        18.12.2014     09:29            Doom
0
votes

You have to add -Recurse

Try this

Get-ChildItem *Folder -Exclude "OtherFolder" -Recurse | %{$_.BaseName}

And if you only whant to return Folders, you have to add -Directory.