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:
Buongiorno ho trovato il vostro articolo molto interessante e utile per un lavoro che devo fare, volevo chiedere un aiuto per fare in modo che il risultato di questa funzione mi restituisca il risultato in un file anzichè a video.
Avreste la possibilità di darmi qualche indicazione al riguardo per favore?
Grazie
buongiorno manuele, non mi è chiara la necessità: il mio esempio fa il parsing di un file, tu vuoi che anche l’output sia scritto su un (secondo) file? In tal caso basta un redirect (>)