Question [Fonction] Highlight-Content

Plus d'informations
il y a 11 ans 4 mois #13079 par Richard Lazaro
Bonsoir,
Cela fait un moment que je n'ai pas eu le temps de poster sur ce forum.

Alors je reviens avec une fonction, il me semblait que benduru avait fait un post challenge concernant une fonction qui affiche en couleur une certaine chaine dans une autre chaine.

Alors voici deux fonctions ci dessous
La première compatible v1 (oui l'opérande -split n'existe pas sous Poshv1 ...)

[code:1]
Function Highlight-Content {
Param(
[String] $Value,
[String] $Pattern,
[String] $Color,
[Switch] $NoNewLine
)

$temp = ''
$cpt = 1
$chars = $Value.ToCharArray()

$chars | ForEach-Object {
$temp += $_

if($temp -eq $Pattern.Substring(0,$cpt)) {
if($Pattern -eq $temp) {
Write-Host $temp -ForegroundColor $Color -NoNewline
$temp = ''
$cpt = 1
} else {
$cpt++
}

} else {
Write-Host $temp -NoNewline
$temp = ''
$cpt = 1
}
}

if(![String]::IsNullOrEmpty($temp)) {
Write-Host $temp -NoNewline
$temp = ''
}

if(!$NoNewLine) {
Write-Host \"\"
}
}
[/code:1]

Et une autre, bien plus simple compatible V2

[code:1]
Function Highlight-Content {
Param(
[String] $Value,
[String] $Pattern,
[String] $Color,
[Switch] $NoNewLine
)

$split = @()
$split += $Value -split $Pattern


for($i=0;$i -lt $split.Count;$i++) {
if($i -ne 0) {
Write-Host $Pattern -ForegroundColor $Color -NoNewline
}

Write-Host $split[$i] -NoNewline
}

if(!$NoNewLine) {
Write-Host \"\"
}
}
[/code:1]

Peut être pas le plus propre et elles ne prennent pas en compte le pipeline pour l'instant (rapport besoin/temps ...)

Donc voilà, si cela peut servir ou si y'a des retours ;)

Bien Cordialement,
Richard Lazaro.

Think-MS : (Get-Life).Days | %{ Learn-More }

\\"Problems cannot be solved by the same level of thinking that created them.\\" - Albert Einstein

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.063 secondes
Propulsé par Kunena