Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Creating an HTML URL from a PowerShell String–#SQLNewBlogger from Blog Posts - SQLServerCentral

Save for later
  • 2 min read
  • 30 Dec 2020

article-image

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

I wrote about getting a quick archive of SQL Saturday data last week, and while doing that, I had some issues building the HTML needed in PowerShell. I decided to work through this a bit and determine what was wrong.

My original code looked like this:

$folder = "E:DocumentsgitSQLSatArchiveSQLSatArchiveSQLSatArchiveClientApppublicAssetsPDF"
$code = ""
$list = Get-ChildItem -Path $folder
ForEach ($File in $list) {
#write-host($File.name)
$code = $code + "<li><a href=$($File.Name)>$($File.BaseName)</a></li>"
}
write-host($code)

This gave me the code I needed, which I then edited in SSMS to get the proper formatting. However, I knew this needed to work.

I

had used single quotes and then added in the slashes, but that didn’t work. This code:

$folder = "E:DocumentsgitSQLSatArchiveSQLSatArchiveSQLSatArchiveClientApppublicAssetsPDF"
$code = ""
$list = Get-ChildItem -Path $folder
ForEach ($File in $list) {
#write-host($File.name)
$code = $code + '<li><a href="/Assets/PDF/$($File.Name)" >$($File.BaseName)</a></li>'
}
write-host($code)

produced this type of output:

<li><a href="/Assets/PDF/$($File.Name)" >$($File.BaseName)</a></li>

Not exactly top notch HTML.

I decided that I should look around. I found a post on converting some data to HTML, which wasn’t what I wanted, but it had a clue in there. The double quotes.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime

I needed to escape quotes here, as I wanted the double quotes around my string. I changed the line building the string to this:

$code = $code + "<li><a href=""/Assets/PDF/$($File.Name)"" >$($File.BaseName)</a></li>"

And I then had what I wanted:

<li><a href="/Assets/PDF/1019.pdf" >1019</a></li>

Strings in PoSh can be funny, so a little attention to escaping things and knowing about variables and double quotes is helpful.

SQLNewBlogger

This was about 15 minutes of messing with Google and PoSh to solve, but then only about 10 minutes to write up.

A good example that shows some research, initiative, and investigation in addition to solving a problem.

The post Creating an HTML URL from a PowerShell String–#SQLNewBlogger appeared first on SQLServerCentral.