I am trying to simply search for files in a network share, but exclude a useless directory. I know there is the -exclude
option for get-childitem
.
However, when I try to run the command get-childitem -recurse -exclude \\\\share\\folder\\excludeddir
, PowerShell ignores the -exclude parameter. Any and all permutations of the exclusion path have been attempted.
Why is powershell ignoring the -exclude parameter? Is there any way to simply exclude a directory without having to write multiple lines of code? And no, the method of piping to | ? { $_.FullName -inotmatch 'excludeddir' }
| ? { $_.FullName -inotmatch 'excludeddir' }
| ? { $_.FullName -inotmatch 'excludeddir' }
is not usable, as it is completely ignored by powershell if it is used within a network share.
You can do the following if you want to exclude all files within a folder called Desktop
.
Get-ChildItem -Recurse -File | Where {
$_.Directory.Name -ne 'Desktop'
} | Select-String -Pattern 'mystring'
Explanation:
The problem with -Exclude
is that it only applies to the leaf item of the current item's path. The online documentation falls short in explaining how -Exclude
works and the idiosyncrasies of it. So if you exclude Desktop
, any file named Desktop
or any folder path that ends with a folder named Desktop
would be excluded. It however, does not exclude any subfolders or subfiles of an excluded directory when -Recurse
is used. I do not know if that is by design or an oversight.
If you are only searching for files, the -File
parameter only returns files. Since FileInfo
objects have a Directory
property, which is a DirectoryInfo
object, you can reference its Name
property to determine the parent directory name of a returned file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.