Month: March 2015

[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 = "   10.10.10.1            ,  10.10.10.2           ,  10.10.10.3    "

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

#This will make:
$Param

#Returns:
10.10.10.1,10.10.10.2,10.10.10.3

UPDATE#1:
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:
$Param

#Returns:
First Name Last Name