Yesterday we saw with a very simple script Windows PowerShell can be used to create an RTF file.

Here was our original script that did that.

$Header=”{rtf1ansiansicpg1252deff0nouicompatdeflang1033{fonttbl{f0fnilfcharset0 Calibri;}{f1fnilfcharset2 Symbol;}}`r`n{*generator Riched20 6.3.9600}viewkind4uc1 “
$Footer=”}”

$Line1=’Hello Worldpar’

$Line2=’How’s it Going?par’

Add-Content –path somefile.rtf –force –value $Header

Add-Content –path somefile.rtf –force –value $Line1

Add-Content –path somefile.rtf –force –value $Line2

Add-Content –path somefile.rtf –force –value $Footer

But we really should make this a lot more portable, we can wrap some functions around these since each and every time we’re just calling up “Add-Content” and passing data as well as a filename.

What we are going to do first is create a function that has only ONE job, to receive data and send it to a file.   This is a pretty simple idea and would look like this.

Function Write-RTFDoc
{
Param($outputfile,$content)

Add-Content -Value $content -Path $Outputfile -Force
}

You might be saying “Uhhhh… you KNOW this is kinda stupid, you’re just calling up ADD-Content which already HAS these parameters.”

This function is actually part of a much larger project in which it could be tasked to launch ANY accessible application for outputting data.   Eventually I might add in Microosft Word or even some XML editor for dropping in output.  Tho this be madness, there’s method to it.

Now here is my challenge.  I actually DON’T want to be passing the Filename each and every time.   I’d like to be able to leverage these functions to run multiple output files.

To bypass this little challenge what I will do is instead of passing the the filename as a parameter, I will have this internal function read a variable from the script called $Filename.   It will like this when we read the content within the function.

Function Write-RTFDoc
{
Param($content)

$OutputFile=$Script:Filename

Add-Content -Value $content -Path $Outputfile -Force
}

With this in place I can just swap out the value $Filename with whatever the file is meant to be called like this.

$Filename=’C:Foomydocument.rtf’

Function Write-RTFDoc
{
Param($content)

$OutputFile=$Script:Filename

Add-Content -Value $content -Path $Outputfile -Force
}

 

$Content=’World Peace Through PowerShell’

Write-RTFDoc $Content

This means I can have multiple files running through the same SERIES of functions.  I said SERIES for a reason.   Check out tomorrow and you’ll see where this is starting to go Smile

Sean
The EnergizedTech