troubleshooting Question

Powershell try to group objects

Avatar of Christophe
ChristopheFlag for France asked on
Powershell
17 Comments1 Solution22 ViewsLast Modified:
Dear Experts,

I am working on a script that gets all content of a folder and create a word document with the result as a table format. Everything works except the sorting. I am trying to use group-object in a table without success.

The result I would like is a table with files grouped by their directories.
I tried to modify sorting or add group but I can'tdo it.

The result I have now:
As you can see, the list of files in test\bureau\test is stopped by the folder "Carte" because of sorting.
I would like to have the files grouped by their parent folders with keeping alphabetical sorting. Do you think it is possible?

please see below my script:

# add a background color to directory rows
Function Add-DirBackground
{
   [CmdletBinding()]
   Param (
      [Parameter(Mandatory, ValueFromPipeline)]
      [string]$Line
   )
   Process
   {
      If ($Line.Contains("*dir*"))
      {
         $Line = $Line.Replace("<tr>", "<tr class=""dir"">")
         $Line = $Line.Replace("*dir*", "")
         
         
      }
      Return $Line
   }
}

$head = @"
 <Title>$Foldername - Folder structure</Title>
<style>
body { font-family:Calibri;
       font-size:11pt; }
td, th { border:1px solid #ddd;
         border-collapse:collapse;
  width: 160px;
 }

th { color:white;
     background-color:#344D59;
     padding-top: 12px;
     padding-bottom: 12px;
     font-size:11pt; }

table { width:1050px; margin-bottom:4px;

border-collapse: collapse
}
h2 {
 font-family:Arial;
 color:#212E53;
 font-size:14pt;
}

h4 {
 font-family:Arial;
 color:#212E53;
 font-size:12pt;
}

.dir {
  background-color: #B8CBD0;
  font-weight: bold;
  font-style: italic;
  font-size:11pt;


}

</style>
"@

# Folder select

Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$FolderBrowser.Description = 'Select the folder containing the data'
$result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{ TopMost = $true }))
if ($result -eq [Windows.Forms.DialogResult]::OK)
{
   $FolderBrowser.SelectedPath
}
else
{
   exit
}

# Variables

$path = $FolderBrowser.SelectedPath
$Foldername = Split-Path -Path $FolderBrowser.SelectedPath -Leaf
$outputfile = "$path\$Foldername.html"
$docfile = "$path\$Foldername" + "-Folder index.docx"
$Folders = get-childitem -Path $path -recurse | where-object { $_.PSIsContainer }
$Files = get-childitem -Path $path -recurse | where-object { -not $_.PSIsContainer }

# Request

$Data = Get-ChildItem -Recurse $path | Sort-Object fullname | Foreach {
   $name = $_.fullName
   #$name = $_.fullName.replace($path,$_.parent)
   $parent = Split-Path $name -parent
   $node = Split-Path $name -leaf
   $dir = $_.PSISContainer
   if ($dir) { $node += '*dir*' }
   $level = ($name.ToCharArray() -eq "\").Count
   [PSCustomObject]([ordered]@{
         level  = $level
         dir    = $dir
         parent = $parent
         node   = $node
      })

}

# Output to HTML

$Data |
Select-Object -Property @{ Name = 'Path'; Expression = { $_.Parent } },
           @{ Name = 'File name'; Expression = { $_.Node } },
           @{ Name = 'Comments'; Expression = { $_.Null } },
           @{ Name = 'Doc'; Expression = { $_.Null } } |
ConvertTo-Html -head $head -Body "<h2>Folder name: $($Foldername)</h2> <td><h4>Folders: $($folders.Count) / Files: $($Files.Count)</h4></td>" | Add-DirBackground | out-file $outputfile

# Convert html to docx

[ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type]
$word = New-Object -ComObject word.application
$word.visible = $false
$Selection = $Word.Selection
$doc = $word.documents.open($outputfile)


# change page orientation to landscape
$doc.PageSetup.Orientation = 1

# Set margins size
$doc.PageSetup.LeftMargin = 25
$doc.PageSetup.RightMargin = 25
$doc.PageSetup.TopMargin = 25
$doc.PageSetup.BottomMargin = 50

# set top row to repeat across pages
$doc.Tables[1].Rows[1].HeadingFormat = -1


$doc.saveas([ref]$docfile, [ref]$SaveFormat::wdFormatDocumentDefault)
$doc.close()
$word.Quit()
$word = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

# Remove HTML file

Remove-Item $outputfile -Force

# open Doc file

ii $docfile

Open in new window


Thank you in advance for your help
Christophe
ASKER CERTIFIED SOLUTION
Dustin Saunders
Co-Founder and Chief Architect

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Top Expert 2016

The Distinguished Expert awards are presented to the top veteran and rookie experts to earn the most points in the top 50 topics.

Join our community to see this answer!
Unlock 1 Answer and 17 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 17 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros