Powershell – Creating a HTML document index
As with all of the tips and fixes that I post, there is a purpose to the information. On this occasion, I needed to send a set of supporting documents out as part of an application. Being the diligent and helpful kind of guy that I am, I thought it would be nice to send an index of the documents along too.
This led me to wondering, would it be possible to dynamically create a HTML index from a set of documents in folder? Turns out you can, see the PowerShell script below:
$files = Get-ChildItem 'c:\temp'
New-Item 'c:\temp\index.html' -ItemType File
Add-Content 'c:\temp\index.html' '<html><head>'
Add-Content 'c:\temp\index.html' '<title>Title of the Index</title>'
Add-Content 'c:\temp\index.html' '</head>'
Add-Content 'c:\temp\index.html' '<Body><H1>Title of the Index</H1>'
foreach ($file in $files)
{
$fileName = $file -replace "\.[^\.]+$"
Add-Content 'c:\temp\index.html' "<a href=""$file"">$fileName</a><br><br>"
}
Add-Content 'c:\temp\index.html' '</body></html>'
Let’s very quickly break it down. First we ask for the folder location where the files are stored:
$files = Get-ChildItem 'c:\temp'
Next we create the *.html file where the index will be written, I have placed it in the same folder and named it appropriately Index.html:
New-Item 'c:\temp\index.html' -ItemType File
Now we start to structure the opening static parts of the HTML file, not completely necessary but always nice:
Add-Content 'c:\temp\index.html' '<html><head>'
Add-Content 'c:\temp\index.html' '<title>Title of the Index</title>'
Add-Content 'c:\temp\index.html' '</head>'
Add-Content 'c:\temp\index.html' '<Body><H1>Title of the Index</H1>'
Now we need to loop through each file in the folder and write a Link in the html index to point to it:
foreach ($file in $files)
{
$fileName = $file -replace "\.[^\.]+$"
Add-Content 'c:\temp\index.html' "<a href=""$file"">$fileName</a><br><br>"
}
You will note the 3rd line of the above uses the -replace parameter on the string, this is to clean up the text for the link and removes the file extension. It is purely aesthetic an addition. Finally, we close off the static elements of the HTML index:
Add-Content 'c:\temp\index.html' '</body></html>'
That is it. Keep an eye out for an extended version of this solution that will:
- Accept user input for the folder location;
- Recurse through the directory looking for sub-directories and structure the index appropriately.