I've found that using $null is impossible for string in PowerShell. While I've worked with workaround as below I wonder if there's better way?
Essentially I need 3 states of string $null, '' (empty), 'some string string'.
- First one means - do not execute.
- 2nd one - clear text
- Replace Text with new value
Below is workaround code where I opted for switch -ClearText. Keep in mind that while I could just not add the Set-WordTextText if field is $null but since I'm doing this in nested scenario I would prefer doing it as $null.
function Remove-WordText {
Param(
[parameter(ValueFromPipelineByPropertyName, ValueFromPipeline)][Xceed.Words.NET.InsertBeforeOrAfter] $Paragraph,
[int] $Index = 0,
[int] $Count = $($Paragraph.Text.Length),
[bool] $TrackChanges,
[bool] $RemoveEmptyParagraph,
[bool] $Supress = $false
)
if ($Paragraph -ne $null) {
Write-Verbose "Remove-WordText - Current text $($Paragraph.Text) "
Write-Verbose "Remove-WordText - Removing from $Index to $Count - Paragraph Text Count: $($Paragraph.Text.Length)"
$Paragraph.RemoveText($Index, $Count, $TrackChanges, $RemoveEmptyParagraph)
}
if ($Supress) { return } else { return $Paragraph }
}
function Set-WordTextText {
param(
[parameter(ValueFromPipelineByPropertyName, ValueFromPipeline)][Xceed.Words.NET.InsertBeforeOrAfter] $Paragraph,
[alias ("S")] [AllowNull()][string] $Text,
[switch] $ClearText,
[bool] $Supress = $false
)
if ($Paragraph -ne $null) {
if (-not [string]::IsNullOrEmpty($Text)) {
if ($ClearText -eq $true) {
Write-Verbose 'Set-WordTextText - Clearing Text $ClearText is True'
$Paragraph = Remove-WordText -Paragraph $Paragraph
}
Write-Verbose "Set-WordTextText - Appending Value $Text"
$Paragraph = $Paragraph.Append($Text)
}
}
if ($Supress) { return } else { return $Paragraph }
}
I essentially execute it within function:
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextText -Text $Text[$i] -ClearText:$ClearText -Supress $false
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextColor -Color $Color[$i] -Supress $false
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextFontSize -FontSize $FontSize[$i] -Supress $false
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextFontFamily -FontFamily $FontFamily[$i] -Supress $false
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextBold -Bold $Bold[$i] -Supress $false
$Paragraph[$i] = $Paragraph[$i] | Set-WordTextItalic -Italic $Italic[$i] -Supress $false
It only executes action if value is not null. So the "wrapper" function can have from 1 to 20 parameters and execute only if the parameter is given.
