July 11, 2025

USEFUL-IT

A blog for USEFUL-IT information

[PS] Removing Multiple White Spaces

Removing multiple white spaces from text is easy in PowerShell.
Simply use -replace operator and look for whitespaces (“\s”) that occur one or more time (“+”), then replace them all with just one whitespace:

PS> '2   N2200-PAC-400W       AC  396.00       33.00   ok' -replace '\s+',' '
2 N2200-PAC-400W AC 396.00 33.00 ok


If you want to replace the multiple white spaces with a semi-colon.
Simply use -replace operator and look for multiple whitespaces (“\s\s+”), then replace the all with a semi-colon

PS> '2   N2200-PAC-400W       AC  396.00       33.00   ok' -replace '\s\s+',';'
2;N2200-PAC-400W;AC;396.00;33.00;ok


The last one is useful if you need to create a [pscustomobject] out of it, by using the -split option

$object = '2   N2200-PAC-400W       AC  396.00       33.00   ok' -replace '\s\s+',';' -split ';'
[pscustomobject] @{
    ID = $object[0]
    Type = $object[1]
    Power = $object[2]
    Max = $object[3]
    Current = $object[4]
    State = $object[5]
    }

ID      : 2
Type    : N2200-PAC-400W
Power   : AC
Max     : 396.00
Current : 33.00
State   : ok

About The Author