[Powershell] Remove Spaces from User Input if you will Build an Array

In one of the scripts I came across, The users have  to input IP addresses in the form of: IP1,IP2,IP3,…etc. The Powershell script will take this input and build an array to be passed to NETSH and other network commands. The problem is, the users will for different reasons enter the IPs in the form of: IP1, IP2, IP3, … adding an extra space after “,” sometimes there’s a leading or trailing spaces from copy and paste from other places. The result is ==> the network commands was failing to process these extra spaces. Anyway, to solve this, and to avoid similar situations, When you are getting a variable from users, it’s a good practice to do some cleanup, because you will never know what users will enter. One good example, is to utilize –replace parameter with \s to remove all spaces, tabs So:

$Param = "            ,           ,    "

#You clean it up by:
$Param = $Param -replace '\s',''

#This will make:


It also worth mentioning that, If you only want to remove the leading and trailing spaces from the users input, Use the Trim() method. So:

$Param = "   First Name Last Name    "

#You clean it up by:
$Param = $Param.trim()

#This will make:

First Name Last Name

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s