Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.[1]
I wrote about getting a quick archive of SQL Saturday data[2] 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[3], which wasn’t what I wanted, but it had a clue in there. The double quotes.
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[4] 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[5] appeared first on SQLServerCentral[6].
References
- ^ #SQLNewBlogger (twitter.com)
- ^ a quick archive of SQL Saturday data (voiceofthedba.com)
- ^ converting some data to HTML (jdhitsolutions.com)
- ^ variables and double quotes (jon.netdork.net)
- ^ Creating an HTML URL from a PowerShell String–#SQLNewBlogger (www.sqlservercentral.com)
- ^ SQLServerCentral (www.sqlservercentral.com)
Source: Programming News