I've a sample code like this:
[string] $Text = "This is a string text with some $($variable.Option) and $otherOption and that's it".
Now what I would like to know is it possible to split that $Text into standard strings and variables separately? So that when I pass this $Text variable to a method it's able to extract $($variable.Option) separately?
I know it's a long shot but maybe it's not being processed right away at assignment time?
The ultimate goal is to create a better version of method I wrote for making colorful powershell:
function Write-Color([String[]]$Text, [ConsoleColor[]]$Color = "White", [int]$StartTab = 0, [int] $LinesBefore = 0,[int] $LinesAfter = 0) {
$DefaultColor = $Color[0]
if ($LinesBefore -ne 0) { for ($i = 0; $i -lt $LinesBefore; $i++) { Write-Host "`n" -NoNewline } } # Add empty line before
if ($StartTab -ne 0) { for ($i = 0; $i -lt $StartTab; $i++) { Write-Host "`t" -NoNewLine } } # Add TABS before text
if ($Color.Count -ge $Text.Count) {
for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine }
} else {
for ($i = 0; $i -lt $Color.Length ; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine }
for ($i = $Color.Length; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $DefaultColor -NoNewLine }
}
Write-Host
if ($LinesAfter -ne 0) { for ($i = 0; $i -lt $LinesAfter; $i++) { Write-Host "`n" } } # Add empty line after
}
Usually I can assign colors by doing something like
write-color -Text "[View][$($singleView.Title)]",
"[Row Limit: $($singleView.RowLimit)]",
"[Paged: $($singleView.Paged)]",
"[Default View: $($singleView.DefaultView)]",
"[Style ID: $($singleView.StyleID)]" -Color Yellow, Green, Red, Gray, Green
But this means I get colors for the whole "line". If i would like to get normal text colors in one color and variables being in second color I would have to do something like this:
write-color -Text "[View: ", "$($singleView.Title)", "]",
"[Row Limit: ", "$($singleView.RowLimit)", "]" `
-Color Yellow, Green, Yellow, Yellow, Green, Yellow
It's not bad.. but I just thought if this can be accomplished in a better way where simple text is one color and variables are the 2nd. If I would want to go even further and have $true being in Green and False being in Red that would also require some parsing.
$Text.$Texthas no knowledge about the variables used to define it.$Text = "This is a string text with some {0} and {1} and that's it".. You can pass that to a funciont and then invoke it with$string -f $variable.option, $variable2