我可以使用此命令递归地获得所有子项目:
Get-ChildItem -recurse
但是有办法限制深度吗?如果我只想重复一个或两个级别,例如?
使用它将深度限制为2:
Get-ChildItem ***,**,*
它的工作方式是它在每个深度2,1和0中返回孩子。
说明:
此命令
Get-ChildItem ***
返回所有物品,深度为两个子文件夹。添加*添加一个其他子文件夹以搜索。
与OP问题一致,要使用Get-Childitem限制递归搜索,您需要指定所有可以搜索的深度。
从PowerShell 5.0开始,您现在可以在Get-ChildItem
中使用-Depth
参数!
您将其与-Recurse
结合起来以限制递归。
Get-ChildItem -Recurse -Depth 2
尝试此功能:
Function Get-ChildItemToDepth {
Param(
[String]$Path = $PWD,
[String]$Filter = "*",
[Byte]$ToDepth = 255,
[Byte]$CurrentDepth = 0,
[Switch]$DebugMode
)
$CurrentDepth++
If ($DebugMode) {
$DebugPreference = "Continue"
}
Get-ChildItem $Path | %{
$_ | ?{ $_.Name -Like $Filter }
If ($_.PsIsContainer) {
If ($CurrentDepth -le $ToDepth) {
# Callback to this function
Get-ChildItemToDepth -Path $_.FullName -Filter $Filter `
-ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
Else {
Write-Debug $("Skipping GCI for Folder: $($_.FullName) " + `
"(Why: Current depth $CurrentDepth vs limit depth $ToDepth)")
}
}
}
}
源
我试图使用Resolve-Path限制Get-Childitem递归深度
$PATH = "."
$folder = get-item $PATH
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName***
$Folders = $PATHs | get-item | where {$_.PsIsContainer}
但这很好:
gci "$PATH****"
这是一个函数,每项输出一行,并根据深度级别的凹痕。它可能更可读。
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
它基于博客文章,实用的powershell:修剪文件树和扩展cmdlets 。
@scanlegentil我喜欢这个。
一些改进将是:
$Depth = 2
$Path = "."
$Levels = "*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host
如前所述,这只会扫描指定的深度,因此此修改是一个改进:
$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2 # How many levels deep to scan
$Path = "." # starting path
For ($i=$StartLevel; $i -le $Depth; $i++) {
$Levels = "*" * $i
(Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
Select FullName
}
您可以使用以下方式:
$path = C: # Path for the
$depth = 0 # Indicates depth, 0 is just the base
Get-ChildItem -Path $path -Depth $depth | Where-Object {$_.Extension -eq ".extension"}