Powershell 返回包含特定文件但不完全递归的目录 [英] Powershell Return directories which contain a specific file but not fully recursive
问题描述
使用以下 Powershell 代码,我试图找到根目录中不包含 robots.txt 的文件夹.通常,我可以递归地执行此操作,但是递归这个庞大的文件夹结构需要 FOREVER.我真正需要的只是第一级,也就是只搜索 C:\Projects 中的文件夹.
Using the following Powershell code, I'm trying to locate folders which do NOT contain robots.txt in the root. Normally, I could do this recursively but it's taking FOREVER to recurse this massive folder structure. What I really need is only the first level, AKA search only the folders found in C:\Projects.
基本上我需要从每组孩子中获取孩子,然后才返回没有 robots.txt 文件的父母.我在这里遇到的问题是嵌套 for 循环中的 $_ 给了我 CWD,而不是我正在搜索的目录的子级.我知道我可能必须在这里使用 -Where ,但我有点不知所措,而且对 powershell 还很陌生.任何帮助表示赞赏!
Basically I need to get children from each set of children, and only then return parents where there was no robots.txt file. The problem I'm having here is my $_ in the nested for loop is giving me the CWD, not the children of the directory I'm searching. I know I might have to use a -Where here but I'm a little over my head and pretty new to powershell. Any help is appreciated!
$drv = gci C:\Projects | %{
$parent = $_; gci -exclude "robots.txt" | %{$_.parent}} | gu
推荐答案
这个单行(为了清楚起见,分散在几个)应该对你有用:
this one-liner (spread over several for clarity) should do the trick for you:
# look directly in projects, not recursively
dir c:\projects | where {
# returns true if $_ is a container (i.e. a folder)
$_.psiscontainer
} | where {
# test for existence of a file called "robots.txt"
!(test-path (join-path $_.fullname "robots.txt"))
} | foreach {
# do what you want to do here with $_
"$($_.fullname) does not have robots.txt"
}
这篇关于Powershell 返回包含特定文件但不完全递归的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!