gpt4 book ai didi

powershell - 在 PowerShell Get-ChildItem -Exclude 不与 -Recurce 参数一起使用

转载 作者:行者123 更新时间:2023-12-03 23:12:15 24 4
gpt4 key购买 nike

enter image description here我想递归搜索所有目录,除了以 _(下划线)开头的目录。

例如:_archive_DO_NOT_DELETE_processing

我使用了下面的代码,但它不起作用。似乎 exclude 不适用于 recurse 。有什么想法吗?

$exclude = @("_*")
$source = "C:\code\Powershell\delete empty folders\New folder\"
$allitems = Get-ChildItem $source -Directory -Exclude $exclude -Recurse
foreach($myItem in $allitems)
{
echo $myItem.fullname
}

输出:

C:\code\Powershell\delete empty folders\New folder\New folder\New folderC:\code\Powershell\delete empty folders\New folder\New folder\New folder\New folderC:\code\Powershell\delete empty folders\New folder\New folder\New folder (2)C:\code\Powershell\delete empty folders\New folder\New folder\New folder (3)C:\code\Powershell\delete empty folders\New folder\New folder\New folder (3)\New folderC:\code\Powershell\delete empty folders\New folder\_archive\New folder

So, as I told before I want to avoid the directory started with underscore, hence the last line should not come.

Even I used below code as well, still same output:

$exclude = @("_*")
$source = "C:\code\Powershell\delete empty folders\New folder\"
$allitems = Get-ChildItem $source -Recurse -Directory |
Where {$_.FullName -notlike $exclude}
foreach($myItem in $allitems)
{
echo $myItem.fullname
}

最佳答案

这里发生的是 Get-ChildItem 的 -exclude 参数基于项目的 name 属性工作。使用通配符时,名称必须与非通配符部分匹配。当您的目录名称以空格开头时,不会发生这种情况。我们来看一个例子:

# Create two files, one starts with a space, the other doesn't
Set-Content -Path " data1.txt" -Value $null
Set-Content -Path "data2.txt" -Value $null

gci -name "data*"
data2.txt

gci -name " data*"
data1.txt

结果是单场比赛,使用了强硬的通配符。原因是data1.txt的第一个字符是空格,与参数的第一个字符不匹配,即d

-exclude 以狡猾而臭名昭著。通过管道将结果传递到 where-object 通常更容易解决。像这样,

Get-ChildItem $source -Directory -recurse | ? {$_.fullname -NotMatch "\\\s*_"} | % { $_.fullname }
# "\\\s*_" is regex for \, any amount of whitespace, _
C:\code\Powershell\delete empty folders\New folder\New folder
C:\code\Powershell\delete empty folders\New folder\New folder\New folder
C:\code\Powershell\delete empty folders\New folder\New folder\New folder (2)
C:\code\Powershell\delete empty folders\New folder\New folder\New folder (3)
C:\code\Powershell\delete empty folders\New folder\New folder\New folder\New folder
C:\code\Powershell\delete empty folders\New folder\New folder\New folder (3)\New folder

Get-ChildItem $source -Directory -recurse | ? {$_.fullname -Match "\\\s*_"} | % { $_.fullname }
C:\code\Powershell\delete empty folders\New folder\ _archive
C:\code\Powershell\delete empty folders\New folder\ _archive\New folder

请注意,匹配需要评估 FullName 属性。仅使用 Name 只会匹配叶级别。

关于powershell - 在 PowerShell Get-ChildItem -Exclude 不与 -Recurce 参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com