从多个文件夹路径生成数组

时间:2018-03-23 20:39:25

标签: powershell

好吧,我对如何让它发挥作用感到困惑。我有几个文件夹位置有多个子文件夹。这些子文件夹都以我们网络上的主机命名。所以我正在编写一个脚本来验证文件夹的内容以供审计。我似乎无法生成一个可用的列表,其中包含从文件夹名称和完整路径名称派生的系统名称。 I.G。

Name        Path
----        ----
system1     \\path\rootfolder1\system1
system2     \\path\rootfolder1\system2
system3     \\path\rootfolder2\system3

我从CSV文件中获取根文件夹,因为文件夹不在一个位置,我不需要在运行报告时使用每个文件夹时间。

#Path to folder repository. Folder names must be the systems host name. 
$list_paths = (Import-Csv 'C:\CVS\path\Paths.csv').path

#list arrays
$list = @()
$list2= @()

#Counters
$p_count = 0
$l_count = 0


#Generates array (list) of folder paths
Foreach ($p1 in $list_paths){
$l_count ++
$listx1 = Get-ChildItem $p1 | Where-Object {$_.PSIsContainer} | Foreach-object {$_.FullName}
$list += $listx1
}

#Generates array (list) of system names from folder
ForEach ($p2 in $list){
$p_count ++
Write-Host $p2
$listx2 = split-path -path $p2 -leaf
$list2 += $listx2
}


$Output = New-Object PSObject -Property @{
        "Name" = $list
        "Path" = $list2
        }

Write-Host ($Output | Format-table | Out-String)

Write-Host Number of root folders
Write-Host $l_count
Write-Host Number of host folders
Write-Host $p_count'

因此,当我运行脚本时,$output会生成此脚本,而不是我想要的格式。

Name
----
{\\path\rootfolder1\system1, \\path\rootfolder2\system2, \\path\root...}

我知道我做错了什么,但我似乎可以弄清楚是什么。

1 个答案:

答案 0 :(得分:0)

您只创建一个具有每个名称和每个路径的对象作为属性值,而不是像第一个示例那样为每个系统文件夹创建一个“名称+路径”对象。此外,您正在混合列表,因此路径最终位于Name - 属性。

尝试在处理系统文件夹的foreach循环中移动New-Object作业。我还建议使用可读的变量名称。

#Path to folder repository. Folder names must be the systems host name. 
$rootpaths = (Import-Csv 'C:\CVS\path\Paths.csv').path

#Systems found
$systems = @()

#Find system-folders inside each root
Foreach ($root in $rootpaths){
    Get-ChildItem $root | Where-Object { $_.PSIsContainer } | Foreach-object {
        #Foreach system-folder, generate a result object
        $systems += New-Object PSObject -Property @{
            #No need to split the path. The object already contains the leaf-name in the Name-property
            "Name" = $_.Name
            "Path" = $_.FullName
        }
    }
}

#No need for write-host if you're writing everything as strings anyways
$systems | Format-table | Out-String

"Number of root folders: $($rootpaths.Count)"
"Number of host folders $($systems.Count)"

正如@TheMadTechnician所提到的,如果使用管道来获取它的价值,实际上可以缩短为:

#Path to folder repository. Folder names must be the systems host name. 
$rootpaths = (Import-Csv 'C:\CVS\path\Paths.csv').path

#Find system-folders inside each root
$systems = Get-ChildItem -Path $rootpaths | Where-Object { $_.PSIsContainer } | Select-Object Name, FullName
#Or this if you have Powershell 3.0+
#$systems = Get-ChildItem -Path $rootpaths -Directory | Select-Object Name, FullName

#No need for write-host if you're writing everything as strings anyways
$systems | Format-table | Out-String

"Number of root folders: $($rootpaths.Count)"
"Number of host folders $($systems.Count)"