Reputation: 351
Hi all I have written the following code to export the text file content to HTML formatted output, but I am not getting the result as expected can some one help me
function TextToHtml {
$SourceFile = "C:\sample.txt"
$TargetFile = "C:\TestOutput.htm"
$TextData = Get-Content $SourceFile
foreach ($Line in $TextData) {
$LineData = $FileLine + $Line
}
$LineData | ConvertTo-HTML | Out-File $TargetFile
}
Upvotes: 0
Views: 4603
Reputation: 174720
ConvertTo-Html
turns object properties into values in a list or table. A string only has one property, Length
- that's what you see the value of in your output.
Create a new object with $LineData
as a property value and you'll get meaningful output
function TextToHtml
{
$SourceFile = "C:\sample.txt"
$TargetFile = "C:\TestOutput.htm"
$TextData = Get-Content $SourceFile
Foreach ($Line in $TextData) {
$LineData = $LineData + $Line
}
New-Object psobject -Property @{Text = $LineData} | ConvertTo-HTML -Property Text | Out-File $TargetFile
}
To make your function more reusable, turn the source and target file paths into parameters.
You also don't need to iterate over each string in $TextData
to append them to each other, just use the -join
operator:
function TextToHtml
{
param(
[string]$SourceFile = "C:\sample.txt",
[string]$TargetFile = "C:\TestOutput.htm"
)
$TextData = Get-Content $SourceFile
$LineData = $TextData -join ''
New-Object psobject -Property @{Text = $LineData} | ConvertTo-HTML | Out-File $TargetFile
}
If you want to avoid the *
header for objects that only have one property, use the -Property
parameter with ConvertTo-Html
to explicitly select the Text
property:
ConvertTo-Html -Property Text
If you want to show each line in it's own table row, skip the concatenation and pipe the strings directly to ConvertTo-Html
instead:
function TextToHtml
{
param(
[string]$SourceFile = "C:\sample.txt",
[string]$TargetFile = "C:\TestOutput.htm"
)
Get-Content $SourceFile | ConvertTo-HTML -Property @{Label='Text';Expression={$_}} | Out-File $TargetFile
}
Upvotes: 2
Reputation: 961
If we go just with the code pasted in the question above. It will give you the value of $FileLine (here it is null or blank) and text from last line in that file.
But if you want to have all lines as well use below code:
function TextToHtml
{
$SourceFile = "C:\sample.txt"
$TargetFile = "C:\TestOutput.htm"
$TextData = Get-Content $SourceFile
Foreach ($Line in $TextData) {
$LineData = $FileLine + $LineData + $Line
}
$LineData | ConvertTo-HTML | Out-File $TargetFile
}
Upvotes: 0