- I. Présentation
- II. Exemples d’utilisation de Trim()
- III. Conclusion
Windows command interpreters
(Be sure to check the “Applies to” section in each article)
Avec PowerShell, la méthode Trim() fait partie des incontournables, au même type que d’autres méthodes que j’ai l’habitude d’utiliser fréquemment : Split(), Substring(), etc.
Ingénieur système et réseau, cofondateur d’IT-Connect et Microsoft MVP “Cloud and Datacenter Management”. Je souhaite partager mon expérience et mes découvertes au travers de mes articles. Généraliste avec une attirance particulière pour les solutions Microsoft et le scripting. Bonne lecture.
Dans ce tutoriel, nous allons apprendre à utiliser la méthode de Trim() de PowerShell qui va s’avérer très utile pour nettoyer une chaine de caractères, que ce soit pour supprimer les espaces inutiles, ou un autre type de caractères.
La méthode Trim() est intégrée nativement dans PowerShell, ainsi que dans d’autres langages, et elle est généralement utilisée pour supprimer les espaces au début et à la fin d’une chaîne de caractères. Ces espaces indésirables peuvent correspondre à un espace unique, mais aussi à une tabulation.
Elle est utile dans différents scénarios, notamment quand le script demande à l’utilisateur de saisir quelque chose (via un Read-Host) ou que vous traitez des données récupérées à partir d’un fichier source.
From Wikipedia, the free encyclopedia


Command-line completion (also tab completion) is a common feature of command-line interpreters, in which the program automatically fills in partially typed commands.
Completable elements may include commands, arguments, file names and other entities, depending on the specific interpreter and its configuration. Command-line completion generally only works in interactive mode. That is, it cannot be invoked to complete partially typed commands in scripts or batch files, even if the completion is unambiguous. The name tab completion comes from the fact that command-line completion is often invoked by pressing the tab key.
You can use the Write-Host cmdlet in PowerShell to output text to the console.
Method 1: Use `t
"This`t string contains a tab"Both of these methods produce the same result.
Example 1: Use `t to Display Tab in PowerShell
- This string contains a tab
"This`t string contains a tab"
Notice that the output displays the text that we specified with a tab in the location where we used `t in the string.
- This string contains a tab

Also notice that this produces the same result as the previous example. Feel free to use whichever method you prefer.
Note: You can find the complete documentation for the Write-Host cmdlet in PowerShell here.
PowerShell: How to Use Write-Host with Specific Colors
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String
You can use the Write-Host cmdlet in PowerShell to output text to the console.
Method 2: Use an Array
Both of these methods produce the same result.
Suppose that you would like to use the Write-Host cmdlet in PowerShell to display text across three lines.

Notice that the output displays the text across three lines, just as we specified.
Example 2: Use Array with Write-Host to Display Multiple Lines
Another way to use the Write-Host cmdlet in PowerShell to display text across multiple lines is to simply declare each line as an element in an array and then pipe the array to the Write-Host cmdlet.

The output displays the text across three lines, just as we specified.
Also notice that this produces the same result as the previous example. Feel free to use whichever method you prefer.
Note: You can find the complete documentation for the Write-Host cmdlet in PowerShell here.
PowerShell: How to Use Write-Host with Specific Colors
PowerShell: How to Use Write-Host and Display Tab Character
PowerShell: How to Replace Text in String
To open the file with Firefox one would type:
firefox introduction-to-command-line-completion.html
This is a long command to type. Instead we can use command-line completion.
First we type the first three letters of our command:
fir
Then we press Tab ↹ and because the only command in our system that starts with “fir” is “firefox”, it will be completed to:
firefox
Then we start typing the file name:
firefox i
But this time is not the only file in the current directory that starts with “i”. The directory also contains files and . The system can’t decide which of these filenames we wanted to type, but it does know that the file must begin with “introduction-to-“, so the command will be completed to:
firefox introduction-to-
Now we type “c”:
firefox introduction-to-c
After pressing Tab ↹ it will be completed to the whole filename:
firefox introduction-to-command-line-completion.html
In short we typed:
firTab ↹iTab ↹cTab ↹
This is just eight keystrokes, which is considerably less than 52 keystrokes we would have needed to type without using command-line completion.
firefox i
We press Tab ↹ once, with the result:
firefox introduction-to-bash.html
We press Tab ↹ again, getting:
firefox introduction-to-command-line-completion.html
In short we typed:
firTab ↹iTab ↹Tab ↹
This is just seven keystrokes, comparable to prompting-style completion. This works best if we know what possibilities the interpreter will rotate through.
I’m looking to change the color of the tab on the currently active tabpage to make it stand out more.
I have set the DrawMode to OwnerDrawFixed and I was able to convert some c# code, found on another question here, to draw the tabs. I have enabled TabControl Selecting and Deselecting actions but those do not receive DrawItem events.
Here is my DrawItem code, if you think it could be optimized let me know, as I’m not the greatest at converting c# to powershell.
$TabControl_DrawItem = {
$CurrentTabPage = $TabControl1.TabPages[$_.Index]
$paddedBounds = New-Object Rectanglef ($_.Bounds.Location,$_.Bounds.Size)
$paddedBounds.Inflate(-2,-2)
$_.Graphics.DrawString($CurrentTabPage.Text, $_.Font, [SolidBrush]::New([Color]::Black), $paddedBounds)}I know how to change the background color of a tab at load time but how do you do it every time a new tab is selected?
$_.Graphics.FillRectangle([SolidBrush]::New([Color]::Yellow), $_.Bounds)Here is my complete test form, thanks in advance.
using namespace System.Windows.Forms
using namespace System.Drawing
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$TabControl_DrawItem = {
$CurrentTabPage = $TabControl1.TabPages[$_.Index]
$paddedBounds = New-Object Rectanglef ($_.Bounds.Location,$_.Bounds.Size)
$paddedBounds.Inflate(-2,-2)
$_.Graphics.DrawString($CurrentTabPage.Text, $_.Font, [SolidBrush]::New([Color]::Black), $paddedBounds)
}
$TabControl_Selecting = { #---Tab is selecting
}
$TabControl_Deselecting = { #---Tab is deselecting
}
$Form1 = New-Object -TypeName Form
$TabControl1 = New-Object -TypeName TabControl
$TabPage1 = New-Object -TypeName TabPage
$TabPage2 = New-Object -TypeName TabPage
$TabPage3 = New-Object -TypeName TabPage
$Form1.Text = "Test-TabControl-Form"
$Form1.ClientSize = (New-Object -TypeName Size -ArgumentList @(632,356))
$Form1.BackColor = [Color]::DimGray
$TabControl1.Name = "TabControl1"
$TabControl1.Size = (New-Object -TypeName Size -ArgumentList @(610,308))
$TabControl1.Location = (New-Object -TypeName Point -ArgumentList @(12,36))
$TabControl1.Multiline = $true
$TabControl1.HotTrack = $true
$TabControl1.SelectedIndex = 0
$TabControl1.TabIndex = 0
$TabControl1.DrawMode = [TabDrawMode]::OwnerDrawFixed
$TabControl1.add_DrawItem($TabControl_DrawItem)
$TabControl1.add_Selecting($TabControl_Selecting)
$TabControl1.add_Deselecting($TabControl_Deselecting)
$TabPage1.Name = "TabPage1"
$TabPage1.Text = "TabPage1"
$TabPage1.Location = (New-Object -TypeName Point -ArgumentList @(4,22))
$TabPage1.Padding = (New-Object -TypeName Padding -ArgumentList @(3))
$TabPage1.Size = (New-Object -TypeName Size -ArgumentList @(391,282))
$TabPage1.TabIndex = 0
$TabPage1.BackColor = [Color]::DimGray
$TabPage2.Name = "TabPage2"
$TabPage2.Text = "TabPage2"
$TabPage2.Location = (New-Object -TypeName Point -ArgumentList @(4,22))
$TabPage2.Padding = (New-Object -TypeName Padding -ArgumentList @(3))
$TabPage2.Size = (New-Object -TypeName Size -ArgumentList @(602,282))
$TabPage2.TabIndex = 1
$TabPage2.BackColor = [Color]::DimGray
$TabPage3.Name = "TabPage3"
$TabPage3.Text = "TabPage3"
$TabPage3.Location = (New-Object -TypeName Point -ArgumentList @(4,22))
$TabPage3.Size = (New-Object -TypeName Size -ArgumentList @(391,282))
$TabPage3.TabIndex = 2
$TabPage3.BackColor = [Color]::DimGray
$Form1.Controls.Add($TabControl1)
$TabControl1.Controls.Add($TabPage1)
$TabControl1.Controls.Add($TabPage2)
$TabControl1.Controls.Add($TabPage3)
$Form1.ShowDialog()Key points
Enabling auto-completion for kubectl and setting an alias will save you time!
Flavius Dinu
Flavius is a passionate Developer Advocate with an Infrastructure as Code mindset and expertise in DevOps & Cloud Engineering. He holds ITIL Foundation Certificate in IT Service Management and Hashicorp Terraform Associate Certification. He currently works at Spacelift, and in his free time, he blogs at techblog.flaviusdinu.com, where he provides tutorials, tips, and tricks for all levels of experience based on his exposure.
Jack Roper
Jack Roper is a highly experienced IT professional with close to 20 years of experience, focused on cloud and DevOps technologies. He specializes in Terraform, Azure, Azure DevOps, and Kubernetes and holds multiple certifications from Microsoft, Amazon, and Hashicorp. Jack enjoys writing technical articles for well-regarded websites.
Completion in different command line interfaces
- Unix shells, including Bash (the default shell in most Linux distributions) and ksh among many others, have a long-standing tradition of advanced and customizable completion capabilities.[3]
- Bash programmable completion,
completeandcompgencommands[4] have been available since the beta version of 2.04[3] in 2000[5] and offers at least Pathname and filename completion. - For KornShell users, file name completion depends on the value of the EDITOR variable. If EDITOR is set to vi, you type part of the name, and then Escape,\. If EDITOR is set to Emacs, you type part of the name, and then Escape,Escape.
- The Z shell (zsh) pioneered the support for fully programmable completion, allowing users to have the shell automatically complete the parameters of various commands unrelated to the shell itself, which is accomplished by priming the shell with definitions of all known switches as well as appropriate parameter types. This allows the user to e.g. type tar xzf Tab ↹ and have the shell complete only tarred gzip archives from the actual filesystem, skipping files which are incompatible with the input parameters. A modern zsh installation comes with completion definitions for over five hundred commands.
- Tcsh offers default file, command, and variable name completion activated using Tab ↹. The ‘complete’ builtin command provides fully programmable completion. The source code comes with a ‘complete.tcsh’ file containing many examples of its completion syntax.
- Bash programmable completion,
- Windows PowerShell, the extensible command shell from Microsoft, which is based on object-oriented programming and the Microsoft .NET framework, provides powerful and customizable completion capabilities similar to those of traditional Unix shells.[6][7][]
- The command processor of Windows NT-based systems supports basic completion. It is possible to use a separate key-binding for matching directory names only.
- cmd.exe /F:ON enables file and directory name completion characters (^F and ^D by default). Use cmd.exe /? for more information.
- TweakUI can be used to configure the keys used for file name and directory name completion.[8]
- The MS-DOS command processor did not have command-line completion: pressing the tab key would just advance the cursor. However, various enhanced shells for MS-DOS, such as 4DOS, the FreeDOS version of , or the Enhanced DOSKEY.COM feature Unix-style tab completion.
- Far Manager apart from its file management functions provides command history and line completion for Windows.
II. Exemples d’utilisation de Trim()
A. Supprimer les espaces
Nous allons commencer par utiliser la méthode Trim() de PowerShell pour éliminer les espaces en début et en fin de chaînes de caractères.
Voici la chaine de caractères que nous allons manipuler :
$Texte = " Tutoriel pour IT-Connect "Nous pouvons constater qu’il y a des espaces à trois endroits : avant le texte (2), après le texte (2), et entre chaque mot. Puisque les espaces sont en quelque sorte “invisibles”, nous allons obtenir la longueur de cette chaine de caractères via la propriété “Length“.
$Texte.Length
# Résultat actuel :
28Maintenant, nous allons appliquer la méthode Trim() sur cette chaine de caractères, stocker, le résultat dans une variable et calculer la longueur de la nouvelle chaine obtenue.
$TexteTrim = $Texte.Trim()
$TexteTrim.LengthCette fois-ci, nous obtenons une valeur différente : 24 au lieu de 28. En effet, la méthode Trim() a supprimé les espaces avant et après le texte, qui sont inutiles, tout en conservant les espaces entre les mots, qui eux sont utiles !
Testez par vous-même avec ces quelques lignes de code :
Write-Host "Sans la méthode Trim()" -ForegroundColor Green$Texte = " Tutoriel pour IT-Connect "
$Texte
$Texte.LengthWrite-Host "Avec la méthode Trim()" -ForegroundColor Green$TexteTrim = $Texte.Trim()
$TexteTrim
$TexteTrim.LengthCe qui donne :

B. Supprimer le caractère de votre choix
Par défaut, Trim() supprime les espaces inutiles (espace, tabulation). Sachez que vous pouvez l’utiliser pour supprimer un caractère spécial de votre choix. Imaginons que nous souhaitons éliminer les “#” en début et fin de chaînes de caractères. Il suffirait d’utiliser la méthode Trim() de cette façon :
$Texte.Trim("#")Vous pouvez tester avec ce bout de code où les espaces sont remplacés par le symbole “#” pour cette démonstration.
Write-Host "Sans la méthode Trim()" -ForegroundColor Green$Texte = "##Tutoriel pour IT-Connect##"
$Texte
$Texte.LengthWrite-Host "Avec la méthode Trim()" -ForegroundColor Green$TexteTrim = $Texte.Trim("#")
$TexteTrim
$TexteTrim.LengthCe qui donne bien le résultat attendu :

Il est important de préciser que dans ce cas, Trim() va supprimer les caractères “#” mais il va conserver les espaces éventuels.
C. Supprimer plusieurs types de caractères
Si vous souhaitez utiliser la méthode Trim() pour supprimer les espaces, ainsi que d’autres caractères, sachez que c’est possible. Dans ce cas, vous devez simplement ajouter dans les parenthèses cette liste de caractères.
Dans l’exemple ci-dessous, nous allons chercher à éliminer les espaces, les “#” et les “?”. Voici un bout de code pour tester :
Write-Host "Sans la méthode Trim()" -ForegroundColor Green
$Texte = "## Tutoriel pour IT-Connect ?"
$Texte
$Texte.Length
Write-Host "Avec la méthode Trim()" -ForegroundColor Green
$TexteTrim = $Texte.Trim("#? ")
$TexteTrim
$TexteTrim.LengthCe qui donne :

Voilà, nous obtenons bien le résultat attendu ! Sachez que Trim() fonctionne aussi avec les lettres et les chiffres. Cette méthode n’est pas réservée aux caractères spéciaux même si nous l’utilisons souvent dans ce but.
D. TrimStart() et TrimEnd()
La méthode Trim() est très pratique, mais elle effectue systématiquement le nettoyage au début et à la fin de la chaîne de caractères. Si vous avez besoin de supprimer uniquement les espaces ou les caractères inutiles au début de la chaîne, ou à l’inverse, à la fin de la chaîne, sachez que vous pouvez utiliser ces deux méthodes :
- TrimStart() pour les caractères au début de la chaîne
- TrimEnd() pour les caractères à la fin de la chaine
La méthode TrimEnd() est utile lorsque l’on manipule des chemins pour supprimer le dernier “\” qui peut être ajouté à la suite du dernier répertoire, ce qui permettra facilement de venir ajouter le nom d’un autre répertoire en le préfixant par “\” sans risquer de se retrouver avec un double “\\”. Ceci nous permet de contrôler que le chemin aura bien le format attendu : si ce chemin est fourni par une saisie utilisateurs, vous avez une chance sur deux que le “\” à la fin soit présent. Avec TrimEnd(), ce problème potentiel est éliminé.
Voici un exemple où l’on élimine le caractère “\”, ce qui oblige à rajouter un caractère d’échappement :
$Chemin = "C:\TEMP\"
$Chemin.TrimEnd("/\")
# Résultat :
C:\TEMPCes deux méthodes fonctionnent sur le même principe et apportent un peu plus de souplesse.
Benefits of using kubectl autocomplete
There are many benefits to using any autocomplete tool, but when it comes to Kubernetes, this is even more helpful, as kubectl commands can take a very long time. Let’s explore some of the benefits:
- Efficiency – reduce the amount of typing required, especially in very long commands
- Minimize errors – by suggesting command completions, you minimize the chances for mistyping, thus reducing overall frustration
- Enhanced learning
- Increased productivity
How to set up kubectl autocomplete in a Linux Bash Shell
First, let’s set up kubectl autocomplete for a Linux Bash Shell
1) Install Kubectl on Linux

Download the latest kubectl release with the command:
-L -s https://dl.k8s.io/release/stable.txtDownload the checksum file:
-L -s https://dl.k8s.io/release/stable.txtValidate the kubectl binary against the checksum file:
-o root -g root -m 0755 kubectl /usr/local/bin/kubectlType kubectl . You should now see the tool is installed.

2) Set up Auto-completion
Check if bash-completion is already installed:

If it is not installed, install using apt or yum, depending on which package manager you are using (usually apt for Ubuntu):
Set the kubectl completion script source for your shell sessions:

3) Set up an alias for kubectl and enable auto-completion
Set an alias for kubectl as k.
Enable the alias for auto-completion.
'complete -o default -F __start_kubectl k'
Kubectl autocomplete in action – examples
To use the kubectl autocomplete, you just need to start typing a command you want to use, and by pressing tab, you will get suggestions for how to autocomplete.

Why is kubectl autocomplete not working?
There are several reasons why kubectl autocomplete may not be working:
- Shell Compatibility – kubectl autocomplete is supported in zsh, bash, and powershell.
- Installation Path – you should ensure that your kubectl executable is accessible in the system PATH.
- Shell aliases – if you are using an alias for kubectl, you might need to also set up autocompletion for that alias.
- Profile not sourced – if you’ve just changed your profile, you need to source it or restart the terminal to ensure autocompletion is working properly.
- Incomplete installation – sometimes autocompletion dependencies may be a part of a different package, so depending on how you’ve installed kubectl, you may need to install something else.
How to set up kubectl autocomplete in PowerShell
To set up kubectl autocomplete in Windows, you just need to run:
kubectl completion powershell How to set up kubectl autocomplete in Mac Zsh
Then, you should edit your zsh profile (~/.zshrc) and add the kubectl autocomplete inside the plugins:

