I'd like to read a string from a line and then put it into a variable which gets used as a filename afterwards. The string is located in a .csv file at the end of the second line. The first line needs to be removed due to unnecessary headings. Also the ';' used in the old .csv file needs to be replaced by a real comma ','. So far I've got the following piece of PowerShell script:
Powershell -command "(gc file1.csv | select -skip 1) -replace ';', ',' | Foreach-Object{ $_ + ',' } | Out-File file2.csv"
Description of code:
gc file1.csv | select -skip 1
gets the content of the csv file. and removes the first line from the temporary array.
-replace ';', ','
replaces all ';' with ','.
Foreach-Object{ $_ + ',' }
adds commas to the end of all lines (which was necessary).
Out-File file2.csv
creates an output file named "file2.csv".
The input file is in the following format: (first 2 lines of the .csv)
123.256.862;;0;568.153.135;12;0;;255.253.233
123.633.582;;0;568.588.533;12;0;;255.253.233
The output file generated by the script is the following: (first 2 lines of the .csv)
123.256.862,,0,568.153.135,12,0,,255.253.233,
123.633.582,,0,568.588.533,12,0,,255.253.233,
Next questions rise when programming in PowerShell:
How can I program this code into multiple lines for readability?
How can I read the last element from the second line and put it into a variable?
Is
$Out-File $variable & '.csv'
correct to generate a new file using this variable as a name? I've tried this method with a dummy variable, but it didn't seem to work. To be more specific: the new filename needs to be 255.253.233.csv.
I've already googled a lot about how to initialize any variable in PowerShell, but it still isn't clear how to exactly declare it afterwards. I hope I'm on the correct path for a solution. Any help is greatly appreciated.
$psversiontable.PSVersion
to get the real version you're running. - alroc$PSVersionTable
. - alroc