Powershell - 将目录路径列表传递给FOR循环 - 将结果输出到CSV

时间:2016-12-06 10:34:52

标签: powershell csv powershell-v4.0

以下代码有效。而不是手动指定路径我想从csv文件E:\ Data \ paths.csv传递一个值列表,然后为处理的每个路径输出单独的csv文件,显示该目录的$ Depth ......

$StartLevel = 0 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 10      # How many levels deep to scan
$Path = "E:\Data\MyPath"     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
$Levels = "\*" * $i
(Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
Select FullName
}

谢谢, 菲尔

2 个答案:

答案 0 :(得分:0)

Get-Help Import-Csv会在这方面为您提供帮助。

的问候,

kvprasoon

答案 1 :(得分:0)

我假设您需要以下内容:

# Create sample input CSV
@"
Path,StartLevel,Depth
"E:\Data\MyPath",0,10
"@ > PathSpecs.csv

# Loop over each input CSV row (object with properties
# .Path, .StartLevel, and .Depth)
foreach ($pathSpec in Import-Csv PathSpecs.csv) {    
    & { For ([int] $i=$pathSpec.StartLevel; $i -le $pathSpec.Depth; $i++) {
      $Levels = "\*" * $i
      Resolve-Path "$($pathSpec.Path)$Levels" | Get-Item | Where PsIsContainer |
          Select FullName  
    } } | # Export paths to a CSV file named "Path-<input-path-with-punct-stripped>.csv"
    Export-Csv -NoTypeInformation "Path-$($pathSpec.Path -replace '[^\p{L}0-9]+', '_').csv"
}

请注意,您在子树中使用广度优先枚举子目录的方法可行,但对于大型子树,这种方法会很慢。