Question:
I have two array’s which contain a selection of strings with information taken from a text file. I then use a For Loop to loop through both arrays and print out the strings together, which happen to create a folder destination and file name.
1 2 |
Get-Content .\PostBackupCheck-TextFile.txt | ForEach-Object { $a = $_ -split ' ' ; $locationArray += "$($a[0]):\$($a[1])\" ; $imageArray += "$($a[2])_$($a[3])_VOL_b00$($a[4])_i000.spi" } |
The above takes a text file, splits it into separate parts, stores some into the locationArray
and other information in the imageArray
, like this:
locationArray[0]
would be L:\Place\
imageArray[0]
would be SERVERNAME_C_VOL_b001_i005.spi
Then I run a For Loop:
1 2 3 |
for ($i=0; $i -le $imageArray.Length - 1; $i++) {Write-Host $locationArray[$i]$imageArray[$i]} |
But it places a space between the L:\Place\
and the SERVERNAME_C_VOL_b001_i005.spi
So it becomes: L:\Place\ SERVERNAME_C_VOL_b001_i005.spi
Instead, it should be: L:\Place\SERVERNAME_C_VOL_b001_i005.spi
How can I fix it?
Answer:
Option #1 – for best readability:
1 2 |
{Write-Host ("{0}{1}" -f $locationArray[$i], $imageArray[$i]) } |
Option #2 – slightly confusing, less readable:
1 2 |
{Write-Host "$($locationArray[$i])$($imageArray[$i])" } |
Option #3 – more readable than #2, but more lines:
1 2 3 4 5 6 |
{ $location = $locationArray[$i]; $image = $imageArray[$i]; Write-Host "$location$image"; } |