好吧,我把我自己弄糊涂了。我有几个文件夹位置,有多个子文件夹。这些子文件夹都是以我们网络上的主机命名的。因此,为了审核目的,我正在编写一个脚本来验证文件夹的内容。我似乎无法生成一个从文件夹名和完整路径名派生出系统名称的可用列表。一.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...}我知道我做错了什么,但我似乎能搞清楚是什么。
发布于 2018-03-23 21:36:44
您只创建一个以每个名称和每个路径作为属性值的对象,而不是像第一个示例那样的每个系统文件夹中的一个“名称+路径”-object。而且,您正在混合列表,因此路径最终出现在Name-property中。
尝试在处理系统文件夹的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)"https://stackoverflow.com/questions/49457982
复制相似问题