Powershell, how to get parameters from a file

by luca
0 comment

I wrote the following snippet when a friend asked me some help: he needed to execute a command several times, getting its parameters from a CSV (comma-separated values) file.

the parameters.csv file contains the following informations:

  • IP address
  • username
  • password

Here’s the script:

$file = Get-Content "C:\parameters.csv"
foreach($row in $file) {
	$parameters = $row.Split(",");
	$ipaddress = $parameters[0];
	$username = $parameters[1];
	$password = $parameters[2];
	echo "Ip address: $ipaddress`tusername: $username`tpassword: $password";

Get-Content cmdlet  returns an array containing input file’s rows. foreach loop runs for every array element and – on each execution – stores a single row in $row variable.

Split is a string object’s method that splits the string into elements using the character you pass (in my example comma char) as separator and returns an elements array.

Finally, each element is stored in a variable (note that the first element in an array has index 0) and its value is printed:

Related Posts

Leave a Comment

6 + two =